或许可以摆脱困境

jup*_*p0r 0 haskell

为什么计算以下表达式会终止?

foldr (\x t -> if x > 5 then Just x else t) Nothing $ [1..]
Run Code Online (Sandbox Code Playgroud)

是否有任何特殊情况Maybe(或其实现的类型类之一)导致 lambda 返回 a 后停止计算Just

chi*_*chi 5

MaybeJustNothing在这里不发挥积极作用。我们看到的只是工作中的懒惰。事实上,对于任何(总)函数f和值a,这也会终止:

foldr (\x t -> if x > 5 then f x else t) a $ [1..]
Run Code Online (Sandbox Code Playgroud)

这完全等同于简单的递归

foo [] = a
foo (x:xs) = if x > 5 then f x else foo xs
Run Code Online (Sandbox Code Playgroud)

当称为foo [1..]. 最终,x变为6,f 6返回,并且不再进行递归调用。