我更喜欢通过查看代码来学习,而不是阅读冗长的解释。这可能是我不喜欢长篇学术论文的原因之一。代码明确、简洁、无噪音,如果你不理解某些东西,你可以直接尝试操作它 - 不需要问作者。
这是Lambda演算的完整定义:
-- A Lambda Calculus term is a function, an application or a variable.
data Term = Lam Term | App Term Term | Var Int deriving (Show,Eq,Ord)
-- Reduces lambda term to its normal form.
reduce :: Term -> Term
reduce (Var index) = Var index
reduce (Lam body) = Lam (reduce body)
reduce (App left right) = case reduce left of
Lam body -> reduce (substitute (reduce right) body)
otherwise -> App (reduce left) (reduce right)
-- Replaces bound variables of `target` by `term` and adjusts bruijn indices.
-- Don't mind those variables, they just keep track of the bruijn indices.
substitute :: Term -> Term -> Term
substitute term target = go term True 0 (-1) target where
go t s d w (App a b) = App (go t s d w a) (go t s d w b)
go t s d w (Lam a) = Lam (go t s (d+1) w a)
go t s d w (Var a) | s && a == d = go (Var 0) False (-1) d t
go t s d w (Var a) | otherwise = Var (a + (if a > d then w else 0))
-- If the evaluator is correct, this test should print the church number #4.
main = do
let two = (Lam (Lam (App (Var 1) (App (Var 1) (Var 0)))))
print $ reduce (App two two)
我认为上面的“reduce”函数比几页的解释更能说明Lambda演算,当初学习时我希望能够直接看它。你还可以看到它实现了非常严格的计算策略,甚至在抽象中也是如此。在这种精神下,如何修改该代码以说明LC可能具有的许多不同评估策略(按名称调用、惰性评估、按值调用、按共享调用、部分评估等)?