haskell - simple example of monad that takes integers -


i writing monad composes functions, f , g, based on explanation of monads (https://www.youtube.com/watch?v=zhuhctr3xq8). explanation stops @ crucial part: compose function (say f) a -> ma (say g) a -> ma, need way convert ma a, take stuff out of monad container (otherwise how feed output of f g??) , not addressed.

assume have f , g map integer , return maybe:

f :: int -> maybe int f = \x -> (just x)  g :: int -> maybe int g = \x -> (just x) 

i want make monad allows me compose f , g, (g o f)(x) (meaning f(g(x))) can evaluated. work need way convert maybe int (the output of f) int can sent g. when maybe container has value in it, pull out value. when g's output nothing, can consider value 0 (i know g's output can't nothing g above lets assume f).

this failed attempt define monad mymonad this:

f :: int -> maybe int f = \x -> (just x)  g :: int -> maybe int g = \x -> (just x)  data mymonad = maybe  instance monad mymonad   return x = mymonad x   x >>= (\x -> mymonad (just x))   nothing >>= (\x -> mymonad (just 0)) 

can clarify wrong here? tutorials it's hard know right way pattern match inside functions (to handle case of vs. nothing here) , tease apart different syntaxes of instantiating monad. example doesn't (https://wiki.haskell.org/all_about_monads#maybe_a_monad): after introducing bind >>= sheep example doesn't use , uses combinator instead.

when first start learning monads, easiest 1 learn called identity monad. looks you're trying implement, you're getting word maybe stuck in there somewhere, , it's throwing off. (that, or trying implement maybe monad, you've not defined just or nothing anywhere.)

if mymonad identity monad, correct definition be:

f :: int -> mymonad int f = \x -> myidentity x  g :: int -> mymonad int g = \x -> myidentity x  data mymonad = myidentity  instance monad mymonad     return x = myidentity x     -- return = \x -> myidentity x     (myidentity x) >>= f = f x  -- (>>=) = \(myidentity x) f -> f x 

if mymonad maybe monad, correct definition be:

f :: int -> mymonad int f = \x -> myjust x  g :: int -> mymonad int g = \x -> myjust x  data mymonad = mynothing | myjust  instance monad mymonad     return x = myjust x     (myjust x) >>= f = f x     mynothing  >>= f = mynothing 

(note, these compile, need define instance functor , applicative.)

p.s. define >>= maybe monad using lambda notation, you'll need case expression:

(>>=) = \m f -> case m of     myjust x  -> f x     mynothing -> mynothing 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -