简体   繁体   中英

Haskell: do notation and return in 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]] .

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 => ma -> (a -> mb) -> mb 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM