我正在尝试编写一个函数,在Lambda演算中执行避免捕获的替换。代码可以编译,但没有给出正确的答案。我已经编写了我期望代码做的事情,我的理解是否正确?
例如,对于这个输入,我应该得到下面的输出(numeral 0
是Church数字0)
*Main> substitute "b" (numeral 0) example -- \a. \x. ((\y. a) x) b
\c. \a. (\a. c) a (\f. \x. x)
-- The incorrect result I actually got
\c. \c. (\f. \x. x) (x (\b. a))
NB由于替换(\y.a)[N/b]
,\y
被重命名为\a
(我想我在编写的代码中已经涵盖了这一点,但如果我错了,请告诉我。)
import Data.Char
import Data.List
type Var = String
data Term =
Variable Var
| Lambda Var Term
| Apply Term Term
-- deriving Show
instance Show Term where
show = pretty
example :: Term -- \a. \x. ((\y. a) x) b
example = Lambda "a"
(Lambda "x" (Apply (Apply (Lambda "y" (Variable "a"))
(Variable "x"))
(Variable "b")))
pretty :: Term -> String
pretty = f 0
where
f i (Variable x) = x
f i (Lambda x m) = if i /= 0 then "(" ++ s ++ ")" else s
where s = "\\" ++ x ++ ". " ++ f 0 m
f i (Apply n m) = if i == 2 then "(" ++ s ++ ")" else s
where s = f 1 n ++ " " ++ f 2 m
substitute :: Var -> Term -> Term -> Term
substitute x n (Variable y)
--if y = x, then leave n alone
| y == x = n
-- otherwise change to y
| otherwise = Variable y
substitute x n (Lambda y m)
--(\y.M)[N/x] = \y.M if y = x
| y == x = Lambda y m
--otherwise \z.(M[z/y][N/x]), where `z` is a fresh variable name
--generated by the `fresh` function, `z` must not be used in M or N,
--and `z` cannot be equal `x`. The `used` function checks if a
--variable name has been used in `Lambda y m`
| otherwise = Lambda newZ newM
where newZ = fresh(used(Lambda y m))
newM = substitute x n m
substitute x n (Apply m2 m1) = Apply newM2 newM1
where newM1 = substitute x n m2
newM2 = substitute x n m1
used :: Term -> [Var]
used (Variable n) = [n]
used (Lambda n t) = merge [n] (used t)
used (Apply t1 t2) = merge (used t1) (used t2)
variables :: [Var]
variables = [l:[] | l <- ['a'..'z']] ++
[l:show x | x <- [1..], l <- ['a'..'z']]
filterFreshVariables :: [Var] -> [Var] -> [Var]
filterFreshVariables lst = filter ( `notElem` lst)
fresh :: [Var] -> Var
fresh lst = head (filterFreshVariables lst variables)
recursiveNumeral :: Int -> Term
recursiveNumeral i
| i == 0 = Variable "x"
| i > 0 = Apply(Variable "f")(recursiveNumeral(i-1))
numeral :: Int -> Term
numeral i = Lambda "f" (Lambda "x" (recursiveNumeral i))
merge :: Ord a => [a] -> [a] -> [a]
merge (x : xs) (y : ys)
| x < y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
merge xs [] = xs
merge [] ys = ys
1条答案
按热度按时间eimct9ow1#
substitute x n (Lambda y m)
中的此部分不正确:z
不能在M
或N
中使用“,但是没有任何东西可以阻止.newZ
成为n
中的变量,这会导致有问题的捕获z/y
修复:
1.“
z
不得用于M
或N
“:1.“
M[z/y][N/x]
”:合计:
请注意,如上所述刷新 all 绑定会使理解结果和调试替换变得困难。实际上,只有当
y
在n
中时,才需要刷新y
。否则,您可以保留y
,并添加以下子句:另一个想法是修改
fresh
,以选择与旧名称相似的名称,例如,通过附加数字,直到其中一个不冲突。还有一个bug我漏了:
newZ
也不应等于x
(最初被替换的变量)。有两种方法可以解决这个问题:
1.将
x
添加到变量集中,以将newZ
排除在以下变量之外:1.如果你仔细想想,这个bug只有在
x
不在m
中时才表现出来,在这种情况下,没有什么可以替换,所以另一种方法是添加一个分支跳过这个工作:合计:
输出量
注意:我还没有尝试证明这段代码是正确的(读者练习:定义“correct”),可能还有我遗漏的bug。一定有一些关于lambda演算的课程有所有的细节和陷阱,但我没有费心去看。