Monday 18 July 2011

Home-made flatten function

OK, the recursive function that flattens:

(defn my-flatten [sq]
  (if (empty? sq)
  '()
  (let [head (first sq)
        tail (rest sq)]
       (if (sequential? head)
          (concat (my-flatten head) (my-flatten tail))
          (cons head (my-flatten tail))))))

So now we have:

user=> (my-flatten '(1 2 3 4 (5 6 ( 7 8 ) 9 10 ) (11 12) 5 6))
(1 2 3 4 5 6 7 8 9 10 11 12 5 6)


Looks about right. So, you transfer a list to another list but if the next element is a list then you flatten this to get the elements out and then concatentate on to the processed version of the rest (you don't cons because this would put the elements back in a list).

No comments:

Post a Comment