Haskell 具有自定义类型的教会数字
Haskell Church Numerals with custom types
我正在尝试解决 Church 数字解析器我有一个自定义类型,它区分变量、lambda 和应用程序
type Var = String
data Term =
Variable Var
| Lambda Var Term
| Apply Term Term
deriving Show
我有一个函数叫做 church
我可以为不同的教堂变体手动定义一个案例。那么让我们说:
church 0
Lambda "f" (Lambda "x" (Variable "x"))
church 1
应该输出 Lambda "f" (Lambda "x" (Apply (Variable "f") (Variable "x")))
church 2
应该输出 Lambda "f" (Lambda "x" (Apply (Variable "f") (Apply (Variable "f") (Variable "x"))))
等等。
我试过递归调用教会函数:
church :: Int -> Term
church 0 = Lambda "f" (Lambda "x" (Variable "x"))
church i = Apply (church(i -1)) (Apply (Variable "f") (Variable "x"))
然而,Lambda "f" (Lambda "x"
的部分也在不断重复
我尝试过的另一种方法是
church :: Int -> Term
church 0 = Lambda "f" (Lambda "x" (Variable "x"))
church i = Apply (church (i -1)) (Apply (Variable "f") (Variable "x"))
然而,这也会产生带有复制的 lambda 的结果。我在这里错过了什么吗?怎么只重复申请部分(Apply (Variable "f") (Variable "x"))
所有教堂数字都以 \f -> (\i -> …)
开头,这意味着我们的函数应该如下所示:
church :: Int -> Term
church n = Lambda f (Lambda x (<strong>go n</strong>))
我们还需要实施的地方 go :: Int -> Term
。因此,这意味着对于 go
我们必须找到一个看起来像这样的函数:
go 0 = Variable "x"
go 1 = Apply (Variable ("f")) (Variable "x")
go 2 = Apply (Variable "x") (Apply (Variable ("f")) (Variable "x"))
所以对于 go <i>n</i>
,我们因此必须 return a Variable "x"
包裹在 n 项 Apply (Variable "x")
因此实现应该如下所示:
go :: Int -> Term
go 0 = Variable "x"
go n = … (go (n-1))
我离开实施 …
作为练习。
我正在尝试解决 Church 数字解析器我有一个自定义类型,它区分变量、lambda 和应用程序
type Var = String
data Term =
Variable Var
| Lambda Var Term
| Apply Term Term
deriving Show
我有一个函数叫做 church
我可以为不同的教堂变体手动定义一个案例。那么让我们说:
church 0
Lambda "f" (Lambda "x" (Variable "x"))
church 1
应该输出Lambda "f" (Lambda "x" (Apply (Variable "f") (Variable "x")))
church 2
应该输出Lambda "f" (Lambda "x" (Apply (Variable "f") (Apply (Variable "f") (Variable "x"))))
等等。
我试过递归调用教会函数:
church :: Int -> Term
church 0 = Lambda "f" (Lambda "x" (Variable "x"))
church i = Apply (church(i -1)) (Apply (Variable "f") (Variable "x"))
然而,Lambda "f" (Lambda "x"
我尝试过的另一种方法是
church :: Int -> Term
church 0 = Lambda "f" (Lambda "x" (Variable "x"))
church i = Apply (church (i -1)) (Apply (Variable "f") (Variable "x"))
然而,这也会产生带有复制的 lambda 的结果。我在这里错过了什么吗?怎么只重复申请部分(Apply (Variable "f") (Variable "x"))
所有教堂数字都以 \f -> (\i -> …)
开头,这意味着我们的函数应该如下所示:
church :: Int -> Term
church n = Lambda f (Lambda x (<strong>go n</strong>))
我们还需要实施的地方 go :: Int -> Term
。因此,这意味着对于 go
我们必须找到一个看起来像这样的函数:
go 0 = Variable "x"
go 1 = Apply (Variable ("f")) (Variable "x")
go 2 = Apply (Variable "x") (Apply (Variable ("f")) (Variable "x"))
所以对于 go <i>n</i>
,我们因此必须 return a Variable "x"
包裹在 n 项 Apply (Variable "x")
因此实现应该如下所示:
go :: Int -> Term
go 0 = Variable "x"
go n = … (go (n-1))
我离开实施 …
作为练习。