我想我理解Haskell中的monad概念,即>>=和return的作用。但是,我对这个Wikipedia 示例中应用它们的语法感到有些困惑。
add :: Maybe Int -> Maybe Int -> Maybe Int
add mx my = -- Adds two values of type (Maybe Int), where each input value can be Nothing
mx >>= (\x -> -- Extracts value x if mx is not Nothing
my >>= (\y -> -- Extracts value y if my is not Nothing
return (x + y))) -- Wraps value (x+y), returning the sum as a value of type (Maybe Int)
我清楚地了解此功能的意图。我只是对评估的顺序有点困惑。任何人都可以逐行显示函数的哪一部分被评估(假设 mx 和 my 的类型是 Maybe Int 并且 mx = Just x' 和 my = Just y',其中 x' 和 y' 是 Int 值)?
我认为是这样的:
mx >>= (\x -> my >>= (\y -> return (x + y))) --- original
(\x -> my >>= (\y -> return (x + y))) x --- mx is Just Int, then apply the function in x
(\x -> my >>= (\y -> return (x + y))) --- x is the first argument. Then I get confused. What's the second part of the function?