Haskell: Make Naming and Returning to Monads

Suppose I have the following code

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

What are the outputs of Just [3,5]

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

+6
source share
1 answer
 do {x <- (Just 3); y <- (Just 5); return (x:y:[])} 

desugars to

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

Since the type >>= is equal to Monad m => ma -> (a -> mb) -> mb and for each argument Just 3 (alternatively Just 5 ), we have m ~ Maybe , the return type of the expression must be some type Maybe .


It is possible to make this return [[3, 5]] using natural transformations from . Since there is 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 just a 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 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 Data.Maybe package as maybeToList .

+18
source

Source: https://habr.com/ru/post/1014966/


All Articles