绑定也可以在do-block中使用,但它在函数中不起作用

eii*_*000 0 haskell

在下面的例子中,"try 0"工作,我得到"Nothing",而"try2 0"不起作用,我得到"Irrefutable模式失败的模式Just(x,y)"我不知道怎么得到"没什么" "from"try 0"...因为"calc n"的输出被绑定到(x,y)...请帮助我理解为什么..

try n = do
  (x,y) <- calc n
  return (x+1, y+1)

try2 n = (x+1,y+1)
  where
    Just (x,y) = calc n

calc x
  | x == 0 = Nothing
  | otherwise = Just (x+1, 1)

main :: IO ()
main = print $ try 0
Run Code Online (Sandbox Code Playgroud)

Laz*_*oke 5

Nothing来自,try因为你Nothing来自calc.该Maybe单子实例(你通过调用do-notation)传播Nothing前进到输出.try2失败,因为您尝试Nothing与模式匹配Just (x,y).这些显然不匹配,因为一个是一个Just,一个是一个Nothing.