Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: do notation and return in Monads

Tags:

haskell

monads

Suppose I have following code

do {x <- (Just 3); y <- (Just 5); return (x:y:[])}

Which outputs Just [3,5]

How does haskell know that output value should be in Maybe monad? I mean return could output [[3, 5]].

like image 313
Atin Avatar asked Feb 14 '17 15:02

Atin


1 Answers

do {x <- (Just 3); y <- (Just 5); return (x:y:[])}

desugars to

Just 3 >>= \x -> Just 5 >>= \y -> return $ x:y:[]

Since the type of >>= is Monad m => m a -> (a -> m b) -> m b and per argument Just 3 (alternatively Just 5) we have m ~ Maybe, the return type of the expression must be some Maybe type.


There is a possibility to make this return [[3, 5]] using something called natural transformations from category theory. Because there exists a natural transformation from Maybe a to [a], namely

alpha :: Maybe a -> [a]
alpha Nothing  = []
alpha (Just a) = [a]

we have that your desired function is simply the natural transformation applied to the result:

alpha (Just 3 >>= \x -> Just 5 >>= \y -> return $ x:y:[])
-- returns [[3, 5]]

Since this is a natural transformation, you can also apply alpha first and your function second:

alpha (Just 3) >>= \x -> alpha (Just 5) >>= \y -> return $ x:y:[]
-- returns [[3, 5]]

As @duplode pointed out, you can find alpha in the package Data.Maybe as maybeToList.

like image 68
ThreeFx Avatar answered Oct 21 '22 20:10

ThreeFx