1

我想我理解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?
4

1 回答 1

3

nm 给出了答案的关键,因为我错误地替换了这些值。

我们必须应用 beta 减少。

引用 Haskell Wiki:

例如,假设我们应用函数

(\x -> 2*x*x + y) 到值 7。为了计算结果,我们用 7 代替 x 的每个自由出现,因此函数 (\x -> 2*x*x) 的应用+ y)(7) 简化为结果

2*7*7 + y

http://www.haskell.org/haskellwiki/Beta_reduction

然后,将其应用于我提出的功能,

mx >>= (\x -> my >>= (\y -> return (x + y)))

(\x -> my >>= (\y -> return (x + y))) x'

my >>= (\y -> return (x' + y)))

(\y -> return (x' + y)) y'

return (x' + y')
于 2014-09-14T08:46:59.060 回答