Scheme(Lazy Racket)一个无限的自然数列表

时间:2013-06-23 06:23:51

标签: lisp scheme racket lazy-evaluation infinite

我认为Lazy Racket应该对处理无限列表很有用。根据{{​​3}},fibs(Fibonacci数的无限列表)可以定义为:

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

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

2 个答案:

答案 0 :(得分:3)

#lang lazy

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

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

答案 1 :(得分:3)

#lang lazy
(define Nat (cons 1 (map (lambda (x) (+ x 1)) Nat)))
感谢Will Ness。

我也找到了

#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)