Haskell do块中的绑定值可能在函数中不起作用时起作用
在下面的示例中,“try 0”起作用,我得到“Nothing”,而“try2 0”不起作用,我得到“pattern Just(x,y)的无可辩驳模式失败” 我不知道我怎么会从“尝试0”中得到“什么都没有”。。。因为“calc n”的输出绑定到(x,y)…请帮助我理解为什么Haskell do块中的绑定值可能在函数中不起作用时起作用,haskell,Haskell,在下面的示例中,“try 0”起作用,我得到“Nothing”,而“try2 0”不起作用,我得到“pattern Just(x,y)的无可辩驳模式失败” 我不知道我怎么会从“尝试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
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
try n=do
(x,y)您从尝试中获得无
,因为您从计算中获得无
。Maybe
Monad实例(通过do
-notation调用)将Nothing
向前传播到输出try2
失败,因为您试图将Nothing
与模式仅(x,y)
匹配。这些显然不匹配,因为一个是只是
,另一个是无
你从中得到无
,因为你从计算中得到无
。Maybe
Monad实例(通过do
-notation调用)将Nothing
向前传播到输出try2
失败,因为您试图将Nothing
与模式仅(x,y)
匹配。这些显然不匹配,因为一个是Just
,一个是Nothing
try
desugas to:try n=calc n>=\(x,y)->return(x+1,y+1)
try
desugas to:try n=calc n>=\(x,y)->return(x+1,y+1)