Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Haskell accessor functions

I'm reading up on Monad tutorials, and the one I'm working on now is http://www.muitovar.com/monad/moncow.xhtml , but I ran on a problem with the state Monad, or to be more precise the runState accessor function.

The type is defined as

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

and it's called e.g.

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

I don't know how to read the definition for getting to the second line, especially because of the "State s a" part. If it where "State a s", I could deduce that the accessor has been curried 'as far' as the 's'.

So the question is; how to read the type definition so that I could see how to call the accessor function in this situation, and if possible how to read accessor functions per se.

like image 624
Masse Avatar asked Dec 10 '22 15:12

Masse


1 Answers

When you have a data type defined as

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

read it like

data T a b = MkT a b

with two helper functions defined automatically:

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

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

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

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

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

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

In the tutorial example,

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

Further reading:

  • Learn You a Haskell: Making Our Own Types and Typeclasses
  • RWH: Defining Types, Streamlining Functions
like image 159
sastanin Avatar answered Dec 29 '22 04:12

sastanin