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.
The expression fmap (*2) is a function that takes a functor f over numbers and returns a functor over numbers. That functor can be a list, a Maybe , an Either String, whatever. The expression fmap (replicate 3) will take a functor over any type and return a functor over a list of elements of that type.
Tuple as a functor Doing this for a pair, which in C# has the type Tuple<T, U> , this means that tuples are functors if we keep T fixed and enable translation of the second element from U1 to U2 . You simply return a new tuple by carrying source.
Functor in Haskell is a kind of functional representation of different Types which can be mapped over. It is a high level concept of implementing polymorphism. According to Haskell developers, all the Types such as List, Map, Tree, etc. are the instance of the Haskell Functor.
String is not a functor, because it has the wrong kind. String :: Type , but a functor has to have kind Type -> Type . Before we talk about Tree , let's establish a few facts. Sum types are functors, if the components are functors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With