5

我认为Lazy Racket对于处理无限列表应该很有用。根据Wikipedia Lazy Racket 文章fibs(斐波那契数的无限列表)可以定义为:

;; An infinite list:
(define fibs (list* 1 1 (map + fibs (cdr fibs))))

我们如何定义一个无限的自然数列表?

4

2 回答 2

3
#lang lazy

(define nats (cons 1 (map 1+ nats)))

显然这不起作用,1+应该替换为(lambda (x) (+ x 1)). 感谢@kenokabe 的测试。(add1是正确的名称。)

于 2013-06-23T06:37:52.043 回答
3
#lang lazy
(define Nat (cons 1 (map (lambda (x) (+ x 1)) Nat)))

感谢威尔·内斯。

我还发现

#lang lazy
;;; infinite sequences represented by a_(n+1) = f(a_n)
(define inf-seq (lambda (a0 f) (cons a0 (inf-seq (f a0) f))))
(define Nat (inf-seq 1 (lambda (x) (+ x 1))))

输出

(define (outputListData list)
   (cond 
       [(null? list) #f] ; actually doesn't really matter what we return
       [else 
            (printf "~s\n" (first list)) ; display the first item ...
            (outputListData (rest list))] ; and start over with the rest
    )
)

(outputListData Nat)
于 2013-06-23T07:06:19.390 回答