Reputation: 1230
In many cases I want to make list by recursion function an I can not find right way how to do it.
For example (Not usefull but shortest I can find) I want to take elements from list one by one and create new list that is same as first one.
(defn f [x] (list
(first x)
(if (not= (rest x) '())
(f (rest x))
'()
)))
(f '(1 2 3))
I want to get
(1 2 3)
but I get
(1 (2 (3 ())))
I want to do not use flatten. For example this imput
(f '([1 1] [2 2] [3 3]))
will be destroyed by flatten.
Upvotes: 2
Views: 159
Reputation: 13890
Replace list
with cons
:
(defn f [x]
(cons (first x)
(if (not= (rest x) '())
(f (rest x))
'())))
Operation (list x y)
returns list of two elements: (x y)
. Operation (cons x y)
returns list which head (i.e. first element) is x
and tail (the rest of the list) is y
where y
should be list itself.
Upvotes: 4