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



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

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

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

#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 "~sn" (first list)) ; display the first item ...
            (outputListData (rest list))] ; and start over with the rest
    )
)
(outputListData Nat)
#lang lazy
(define nats (cons 1 (map 1+ nats)))

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

最新更新