Friday, 15 July 2011

clojure - How to make list by recursion? -



clojure - How to make list by recursion? -

in many cases want create list recursion function can not find right way how it.

for illustration (not usefull shortest can find) want take elements list 1 1 , create new list same first one.

(defn f [x] (list (first x) (if (not= (rest x) '()) (f (rest x)) '() ))) (f '(1 2 3))

i want get

(1 2 3)

but get

(1 (2 (3 ())))

i want not utilize flatten. illustration imput

(f '([1 1] [2 2] [3 3]))

will destroyed flatten.

replace list cons:

(defn f [x] (cons (first x) (if (not= (rest x) '()) (f (rest x)) '())))

operation (list x y) returns list of 2 elements: (x y). operation (cons x y) returns list head (i.e. first element) x , tail (the rest of list) y y should list itself.

clojure lisp

No comments:

Post a Comment