正确使用>>在Haskell

正确使用>>在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) 

我非常努力破译此错误消息...谁能与>>正确使用帮助?我对此不了解的是什么?

+0

好,因为''>>因素已经指出,'\ _ - >'你不必给它明确写入。 –

(>>=)有型号Monad m => m a -> (a -> m b) -> m b。在你的例子中mMaybe所以你提供了一个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 
+0

啊谢谢你!对不起,如果这本身需要一个完整的问题,但是这到底是什么呢? “Just 1”只是10'的目的是什么,只是“Just 10”没有? –

+0

@TheHelpfulBees - 查看更新。 – Lee

+0

@TheHelpfulBees,'也许'可能不是考虑'>>'的最好例子。你可能会更多地考虑它为'State'','Writer w'或'IO'做什么。一旦你理解了这个模式,你就能够看到它以一种相当无趣的方式应用于''a'',它的无聊表姐'Maybe',甚至更琐碎的'Reader e'和'Identity'。 – dfeuer