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:
- in
monad (state state)state monad's name? how relatednewtype state ...? - in
return x = let f t = (t,x) in state ftcomes 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:
instance monad (integer) ...forbidden becauseintegerhas kind*.instance monad (maybe) ...allowed becausemaybehas kind* -> *.instance monad (state) ...forbidden becausestatehas kind* -> * -> *.instance monad (state st) ...allowed becausestate sthas 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
Post a Comment