如何使教堂数字在 lisp 中更易于阅读?

发布于 2024-08-29 12:31:14 字数 333 浏览 0 评论 0原文

我可以使用方案相当容易地定义教堂数字:

> (define f (lambda (x) x))
> (f f) ;0
#<procedure:f>
> (f (f f)) ;1
#<procedure:f>

但是,这并不容易识别 (ff) 是 0 且 (f (ff)) 是 1。有没有一种方法可以我可以让这些数字更易读吗?理想的情况是:

> (f f)
0
> (f (f f))
1

这个例子在方案中,但我会用任何 lisp 来回答。

I can define church numerals fairly easy using scheme:

> (define f (lambda (x) x))
> (f f) ;0
#<procedure:f>
> (f (f f)) ;1
#<procedure:f>

However, this doesn't make it very easy to recognize that (f f) is 0 and (f (f f)) is 1. Is there a way that I can make these numerals more readable? What would be ideal is this:

> (f f)
0
> (f (f f))
1

The example is in scheme, but I'll take an answer in any lisp.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

书信已泛黄 2024-09-05 12:31:14

首先让我们定义真正的教堂数字,它具有 0 != 1 的理想属性:

(define zero (lambda (f x) x))
(define (succ cn) (lambda (f x) (f (cn f x))))

因此 zero 是 0 的教堂表示,(succ Zero) 1,(succ (succ 零)) 2 等等。

现在,由于这些只是函数,因此无法告诉 repl 将它们显示为数字,但您可以定义一个函数 cn-to-int ,它将教堂数字转换为整数,然后可以正常显示:

> (define (cn-to-int cn) (cn (lambda (x) (+ x 1)) 0))
> (cn-to-int zero)
0
> (cn-to-int (succ zero))
1
> (cn-to-int (succ (succ zero)))
2

First let's define real church numerals which have the desirable property that 0 != 1:

(define zero (lambda (f x) x))
(define (succ cn) (lambda (f x) (f (cn f x))))

So zero is the church representation of 0, (succ zero) of 1, (succ (succ zero)) of 2 and so on.

Now since those are just functions, there is no way to tell the repl to display them as numbers, but you can define a function cn-to-int which converts church-numerals to ints which can then be displayed normally:

> (define (cn-to-int cn) (cn (lambda (x) (+ x 1)) 0))
> (cn-to-int zero)
0
> (cn-to-int (succ zero))
1
> (cn-to-int (succ (succ zero)))
2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文