Course map
miso // 10

Lenses and the Effect monad

Read

Updating a record model

Most models are records with several fields. Miso.Lens gives each field a lens: a value that knows how to get and set that field. The update function then reads like imperative code while staying pure.

data Model = Model
  { _count :: Int
  , _label :: MisoString
  } deriving (Show, Eq)

count :: Lens Model Int
count = lens _count $ \m x -> m { _count = x }

label :: Lens Model MisoString
label = lens _label $ \m x -> m { _label = x }

update :: Action -> Effect () () Model Action
update Increment = count += 1
update Rename    = label .= "renamed"
update Double    = count %= (* 2)

.= sets, += adds, %= applies a function. Reading a field is use: n <- use count. The Effect monad is where these live; it is also where IO is scheduled, which the next miso lesson covers.

01 / 04