正确使用>>在Haskell
问题描述:
刚刚被介绍给哈斯克尔的单子,并与>>
碰到了一些障碍。正确使用>>在Haskell
>>=
对我来说很有意义,因为我可以得到下面的出前奏曲:
Prelude> Just 1 >>= (\ x -> Just (x+1))
Just 2
我的理解是,>>
是一样的绑定,但仅用于当函数是关于恒定的参数。但是,当我尝试这样做,在前奏:
Prelude> Just 1 >> (\_ -> Just 10)
<interactive>:7:12: error:
• Couldn't match expected type ‘Maybe b’
with actual type ‘t0 -> Maybe Integer’
• The lambda expression ‘\ _ -> Just 10’ has one argument,
but its type ‘Maybe b’ has none
In the second argument of ‘(>>)’, namely ‘(\ _ -> Just 10)’
In the expression: Just 1 >> (\ _ -> Just 10)
• Relevant bindings include
it :: Maybe b (bound at <interactive>:7:1)
我非常努力破译此错误消息...谁能与>>
正确使用帮助?我对此不了解的是什么?
答
(>>=)
有型号Monad m => m a -> (a -> m b) -> m b
。在你的例子中m
是Maybe
所以你提供了一个Maybe Int
和一个函数Int -> Maybe Int
。
(>>)
的类型为Monad m => m a -> m b -> m b
所以您需要通过Maybe b
而不是返回Maybe b
例如Maybe b
的函数。
Just 1 >> Just 10
在这种情况下,这是一样的Just 10
但如果第一个值是Nothing
的结果也将是Nothing
:
Nothing >> Just 10
你通常会使用(>>)
如果第一个值代表了你一定的效果想要执行并忽略结果,例如IO
。
putStrLn "Hello world" >> pure 10 :: IO Int
或State
:
put "state" >> pure 10 :: State String Int
好,因为''>>因素已经指出,'\ _ - >'你不必给它明确写入。 –