Clojure中的递归斐波纳契函数 [英] a recursive Fibonacci function in Clojure
问题描述
我是clojure的新人,他想看看所有的惊喜。想要获得感觉的最好方法是写一些简单的代码,我想我会从一个斐波纳契函数开始。
我的第一个努力是:
(defn fib [x,n]
(if(<(count x)n)
fib(conjx(+(last x)(nth x( - (count x)2))))n)
x))
要使用这个,我需要在调用函数时用[0 1]种子x。我的问题是,没有将它包装在一个单独的函数,是否可以写一个单一的函数,只需要返回的元素数量?
我可以通过一些更好的方式实现相同的功能:
(defn fib2 [n]
(loop [x [ 0 1]]
(if(<(count x)n)
(recur(conjx(+(last x)(nth x( - (count x)2))))
x)))
和
(defn fib3 [n]
(取n
(首先映射(iterate(fn [[ab]] [b(+ ab)]) ])))
无论如何,我有一个更好的版本的纯递归斐波纳契函数?
解决方案回答你的第一个问题:
(defn fib
([n]
(fib [0 1] n))
([x,n]
(if(<(count x)n)
(fib(conj x(+(last x)(nth x( - (count x)2))))n)
x) )
这种类型的函数定义被称为多元函数定义。您可以在此处了解详情: http://clojure.org/functional_programming
至于一个更好的Fib函数,我认为你的fib3函数是非常真棒,显示了很多函数式编程概念。
I'm a newcomer to clojure who wanted to see what all the fuss is about. Figuring the best way to get a feel for it is to write some simple code, I thought I'd start with a Fibonacci function.
My first effort was:
(defn fib [x, n] (if (< (count x) n) (fib (conj x (+ (last x) (nth x (- (count x) 2)))) n) x))
To use this I need to seed x with [0 1] when calling the function. My question is, without wrapping it in a separate function, is it possible to write a single function that only takes the number of elements to return?
Doing some reading around led me to some better ways of achieving the same funcionality:
(defn fib2 [n] (loop [ x [0 1]] (if (< (count x) n) (recur (conj x (+ (last x) (nth x (- (count x) 2))))) x)))
and
(defn fib3 [n] (take n (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))))
Anyway, more for the sake of the exercise than anything else, can anyone help me with a better version of a purely recursive Fibonacci function? Or perhaps share a better/different function?
解决方案To answer you first question:
(defn fib ([n] (fib [0 1] n)) ([x, n] (if (< (count x) n) (fib (conj x (+ (last x) (nth x (- (count x) 2)))) n) x)))
This type of function definition is called multi-arity function definition. You can learn more about it here: http://clojure.org/functional_programming
As for a better Fib function, I think your fib3 function is quite awesome and shows off a lot of functional programming concepts.
这篇关于Clojure中的递归斐波纳契函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!