Understanding Haskell Access Functions

I am reading Monad tutorials, and the one I'm working on now is http://www.muitovar.com/monad/moncow.xhtml , but I ran further the Monad state problem, or rather, the accessStar runState function.

Type is defined as

newtype State sa = State { runState :: (s -> (a,s)) } 

and it is called, for example.

 runState (chncasewst3 'e' 'd' 'f') False 

I don’t know how to read the definition to go to the second line, especially because of the “State sa” part. If this is where "State as", I can conclude that the accessory was "as far" as "s".

So the question is: how to read the type definition so that I can see how to call this function in this situation, and, if possible, how to read the access functions as such.

+4
source share
1 answer

If you have a data type defined as

 data T ab = MkT { getA :: a, getB :: b } 

read it as

 data T ab = MkT ab 

with two helper functions automatically detected:

 getA :: (T ab) -> a getA (MkT x _) = x getB :: (T ab) -> b getB (MkT _ y) = y 

When you apply getA to a value of T , the result is of type a .

Now your State type consists of only one element, the type of which is a function ( :: s -> (a, s) ). runState converts a value of type State sa to a function of this type.

 ghci> :t runState runState :: State sa -> s -> (a, s) 

Each time you apply runState to a value of type State sa , the result is a function of type s -> (a,s) . And the first argument to this function is the initial value of the state variable (type s ).

In a case study

  • chncasewst3 'e' 'd' 'f' is of type State Bool String .
  • So runState (chncasewst3 'e' 'd' 'f') is of type Bool -> (String, Bool) .
  • So runState (chncasewst3 'e' 'd' 'f') False is of type (String, Bool) .

Further reading:

+12
source

Source: https://habr.com/ru/post/1315576/


All Articles