Clearing Clojure Function

Based on imperative programming languages, I try to wrap my head around Clojure in the hope of using it for my multi-threaded capabilities.
One of the problems with 4Clojure is to write a function that generates a list of Fibonacci numbers of length N, for N> 1. I wrote a function, but given my limited background, I would like to know if this is the best way to Clojure to do things. The code is as follows:

(fn fib [x] (cond 
               (= x 2) '(1 1)
            :else   (reverse (conj (reverse (fib (dec x))) (+ (last (fib (dec x))) (-> (fib (dec x)) reverse rest first))))
          ))
+5
source share
4 answers

, , , , .

, , '(1 1). Clojure iterate , :

user> (doc iterate)
-------------------------
clojure.core/iterate
([f x])
  Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects

, -, , , .

(fn [[x y & _ :as all]] (cons (+ x y) all))

, x y , , , , _, , , all.

iterate , -, ; .

(defn fib [n]
   (nth (iterate (fn [[x y & _ :as all]] (cons (+ x y) all)) '(1 1)) (- n 2)))

, ; , reverse, .

: , , , :

(defn fib [n]
   (nth (iterate (fn [all]
                   (conj all (->> all (take-last 2) (apply +)))) [1 1])
        (- n 2)))
+4

"" , , , n , :

(take n some-infinite-fibonacci-sequence)

fibonnaci :

http://en.wikibooks.org/wiki/Clojure_Programming/Examples/Lazy_Fibonacci

, :

 (defn fib [n]
   (let [next-fib-pair (fn [[a b]] [b (+ a b)])
         fib-pairs (iterate next-fib-pair [1 1])
         all-fibs (map first fib-pairs)]
     (take n all-fibs)))


 (fib 6)
 => (1 1 2 3 5 8)

, , Clojure , .

+7

Fibonacci, ( clojure wikibook: http://en.wikibooks.org/wiki/Clojure_Programming)

 (def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))

: , . , ( )

0 1 1 2 3 5 8 ...
1 1 2 3 5 8 ...
-----------------
1 2 3 5 8 13 ... 

. [0 1] ( [1 1] , ), , . , .

, ( ) .

: fib

 (defn fib [n] (nth fib-seq n)) 
+5

See Christoph Grand Fibonacci's decision in the Clojure Stu Halloway Program. This is the most elegant solution I've seen.

(defn fibo [] (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
(take 10 (fibo))

Also see

How to generate a Fibonacci sequence using Clojure?

+4
source

All Articles