Thursday, 7 July 2011

Flatten a Sequence - hmm

As for the requirement to create code that flattens a nested sequence into a flat sequence - but without using the function flatten - I couldn't think of a way to do this without bringing in a recursive function. Therefore I cheated and looked at the source code for the function flatten. It turns out that there is a Clojure function tree-seq than negotiates trees for you, thereby doing the hard bit of climbing your tree and fetching it down
in branches. So my solution is a fraud as I looked it up:

  (complement sequential?)
  (rest (tree-seq sequential? seq %)))

Of course it also helps to find the predicate sequential?, which is the general purpose tester for the compound data structures list vector etc. Now to atone for cheating I should write the recursive function anyway.

No comments:

Post a Comment