简体   繁体   English

加入Haskell的不同单子

[英]join for different monads in Haskell

I know I can use join to remove the first level of list 我知道我可以使用join删除列表的第一级

join [["dog"]] " output ["dog"] join [["dog"]] “输出["dog"]

But why the following is not working 但是为什么下面的方法不起作用

join $ (Just ["dog"]) 

got error:
Couldn't match type ‘[]’ with ‘Maybe’

We know Maybe and [] are both Monad in Haskell, 我们知道Maybe[]都是Haskell的Monad,

join(Monad m)=> m(m a) -> m a

Maybe is Monad Maybe是莫纳德

[] is Monad []是Monad

What is wrong with that? 怎么了

It seems to me join only for the same type of Monad, please correct me if I'm wrong. 在我看来,只加入相同类型的Monad,如果我错了,请纠正我。

Is there any function similar to join for any Monads like the example I's given above? 是否有类似以上我上面给出的示例的Monad的类似函数?

I know I can do it as following 我知道我可以做到以下

fromJust (Just ["dog"]) 

"output:  ["dog"]

But I need to know Just in advance. 但是我需要提前知道。

The m in join :: Monad m => m (ma) -> ma is the same Monad everywhere it appears. 连接中的m join :: Monad m => m (ma) -> ma在所有出现的地方都是相同的Monad。 If you had Just (Just "dog") , then you have two Maybe monads and your join will work perfectly. 如果您只有Just (Just "dog") ,那么您有两个Maybe monad,并且您的join将完全正常。 Similarly to your list example. 与您的列表示例类似。

Pulling things out of a Monad cannot be generalized, which is part of the power of Monads. 不能一概而论,这是Monad力量的一部分。 Consider that if you could do that, it would be trivial to strip out the type safety of the IO Monad! 考虑一下,如果可以这样做,那么剥夺IO Monad的类型安全性将是微不足道的!

To go from Just ["dog"] -> ["dog"] , you just need a Maybe a -> a You could use Data.Maybe.fromJust , but maybe is safer (what if you have Nothing instead?) 要从Just ["dog"] -> ["dog"] ,您只需要一个Data.Maybe.fromJust Maybe a -> a您可以使用Data.Maybe.fromJust ,但是maybe更安全(如果Nothing怎么办?)

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

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