6
instance Functor (State s) where
 fmap f (State g) = State $ \s0 -> 
 let (a, s1) = g s0
 in (f a, s1)

It is implementation of Functor for State. I cannot understand how does it work? Especially, g is used as it would be a function but on my eye it is not a function. It is just object ( perhaps function) but I cannot understand why it is function. After all, it should be some state so it can for example Int

Please make clear.

Cactus
27.8k10 gold badges74 silver badges165 bronze badges
asked Apr 13, 2016 at 20:48
2
  • 1
    Usually you have State s a = State (s -> (s, a)) so indeed g is a function with type s -> (s, a) (i.e. it takes a state and produces a result (a in this case) and a new state (s1)). This Functor instance simply applies f to the result of the computation before returning the value. Commented Apr 13, 2016 at 20:59
  • The name state is indeed confusing and the state is a monad itself. What is a monad is something which access and or modify a state. Commented Apr 13, 2016 at 22:07

1 Answer 1

10

It looks like your state type looks like:

data State s a = State (s -> (a ,s))

so your fmap function should have type:

fmap :: (a -> b) -> (State s a) -> (State s b)

when you match on the input state value in

fmap f (State g) = State $ \s0 -> 

g is a function s -> (a, s) and you need to construct one of type s -> (b, s).

(a, s1) = g s0

applies the input state to the existing stateful computation, binding a to the result and s1 to the new state. It then applies f to a to obtain the mapped result value in

(f a, s1)

while the state returned from g is unchanged.

answered Apr 13, 2016 at 21:04
Sign up to request clarification or add additional context in comments.

1 Comment

"while the state is unchanged." is somewhat ambiguous. "while the state originally returned by g is unchanged" could be better.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.