简体   繁体   English

哈斯克尔:在莫纳德做符号并返回

[英]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] 哪个输出Just [3,5]

How does haskell know that output value should be in Maybe monad? haskell如何知道输出值应该在Maybe monad中? I mean return could output [[3, 5]] . 我的意思是return可以输出[[3, 5]]

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

desugars to des to to 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. 由于>>=的类型是Monad m => ma -> (a -> mb) -> mb和每个参数Just 3 (或者Just 5 )我们有m ~ Maybe ,表达式的返回类型必须是一些Maybe类型。


There is a possibility to make this return [[3, 5]] using something called natural transformations from category theory . 有可能使用类别理论中的 自然变换来回报[[3, 5]] Because there exists a natural transformation from Maybe a to [a] , namely 因为存在从Maybe a[a]的自然转换,即

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 ,然后再应用第二个函数:

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 . 正如@duplode指出的那样,你可以在包Data.Maybe找到alpha作为maybeToList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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