新手Clojure问题。以下两种实现/表示斐波那契数列的方式有什么优缺点?(特别是,有没有任何东西完全排除其中一个作为坏主意的可能性。)
(ns clxp.fib
(:gen-class))
; On the one hand, it seems more natural in code to have a function that
; returns 'a' Fibonacci sequence.
(defn fib-1
"Returns an infinite sequence of Fibonnaci numbers."
[]
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
; > (take 10 (fib-1))
; (0 1 1 2 3 5 8 13 21 34)
; On the other hand, it seems more mathematically natural to define 'the'
; Fibonacci sequence once, and just refer to it.
(def fib-2
"The infinite sequence of Fibonnaci numbers."
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
; > (take 10 fib-2)
; (0 1 1 2 3 5 8 13 21 34)
a) 定义无限序列的这两种方法各有利弊。需要注意的是,这个特定序列不需要提供任何参数,与例如“n”的倍数无限序列不同,后者需要使用第一种方法以指定“n”的值。
b) 有没有什么总体原因更倾向于其中一种实现方式?(内存消耗、作为参数时的适用性等)
fib-1
,只是为了有它的存在,如果你决定需要一个不可垃圾回收实例,你可以通过(def fib-2 (fib-1))
来定义fib-2
。 - Dax Fohl