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
.
source share