haskell - Understanding a monad instance -


i have haskell code portion:

newtype state st = state (st -> (st, a))  instance monad (state state)     return x = let f t = (t,x) in state f      state f >>= g = state (\oldstate ->                 let {(newstate, val) = f oldstate;                   state f'= g val}                 in f' newstate) 

i'm new monad think got how return , bind works in general case.

but in example above have lots of problems:

  1. in monad (state state) state monad's name? how related newtype state ... ?
  2. in return x = let f t = (t,x) in state f t comes from?

so point you've heard of currying or partial application: if have f :: -> b -> c , x :: a, f x :: b -> c. i.e., if f two-argument function , x has type of f's first argument, f x function takes second argument , "completes" application.

well, in haskell same thing applies type constructors state. types , type constructors have kind, analogous how values have types. non-parametric type integer has kind *; one-parameter type maybe has kind * -> *; state has kind * -> * -> *.

and then, state state partial application of state type constructor, , has kind * -> *. monad class applies kind * -> *. so, applied our examples:

  1. instance monad (integer) ... forbidden because integer has kind *.
  2. instance monad (maybe) ... allowed because maybe has kind * -> *.
  3. instance monad (state) ... forbidden because state has kind * -> * -> *.
  4. instance monad (state st) ... allowed because state st has kind * -> *.

how know monad applies types of kind * -> *? can infer class declaration:

class monad m     return :: -> m     (>>=) :: m -> (a -> m b) -> m b     -- ... 

look @ how m used in class declaration: part of m a , m b, i.e., taking 1 argument. because of this, haskell infers m type variable of kind * -> *.

compare this:

class num     (+) :: -> ->     (-) :: -> ->     -- ... 

here type variable a not applied other type variables—thus must of kind *.

so strictly speaking, state not monad; it's two-place type constructor that, when partially applied 1 type, gives monad. state state monad, state integer, state [a], etc. people speak loosely , talk of state , similar things monads, though, should understand it's parametrized monad—it's monad has internal type parameter , many variants differ in type of parameter.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -