scheme - Scheme 中的斐波那契数列流

标签 scheme lisp racket

我目前正在尝试理解方案中流的概念。例如,我应该编写一个函数 fibonacci,它返回斐波那契数作为流表示形式。

函数的期望输出/用法如下所示:

> (define a (finbonacci))
> a
((0 0) . #<promise>)
> (tail a)
((1 1) . #<promise>)
> (tail (tail a))
((2 1) . #<promise>)

所以每个流元素代表一对n fib(n)

流是这样预定义的:

(define the-empty-stream '())

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream x y)
     (cons x (delay y)))))

(define head car)
(define (tail s) (force (cdr s)))
(define empty-stream? null?) 

我目前非常基本的解决方案尝试如下:

(define fibo
    (cons-stream 1
                 (cons-stream 1
                              (map + fibo (tail fibo))))))

但即使这可以计算任何东西,我也不知道如何将 n 传递到输出或后续流中。

最佳答案

您走在正确的道路上。唯一需要调整的是递归定义的精确表述。

考虑以下内容(其中 --- 表示我们正在添加):

1 1 2 3 5   8  ...   fib
1 2 3 5 8  13  ...   (stream-rest fib)
------------------   ---------------------------------
2 3 5 8 13 21  ...   (stream-rest (stream-rest fib))

注意 (stream-rest (stream-rest fib))fib(stream-rest fib) 的总和。 这意味着我们可以将 fib 定义为:

(define fib (stream-cons 1 (stream-cons 1 (stream-add fib (stream-rest fib)))))

关于scheme - Scheme 中的斐波那契数列流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53583457/

相关文章:

lisp - 在列表中查找元素的 Scheme 函数是什么?

r - Common Lisp 的统计包

recursion - 检查 Racket 中列表的升序

function - 为什么有些?在 Clojure 中将 false 作为参数时返回 true?

user-interface - Racket 中的游戏编程

bash - 使用系统执行某些操作时如何防止代码注入(inject)?

方案将元素添加到列表的末尾

function - Emacs Lisp 可以将 lambda 形式分配给 Scheme 之类的变量吗?

coding-style - 使用 Scheme 代码求解二次方程?

racket - Racket 契约(Contract)依赖性评估两次?