Hi Mike,

If I understood your aim correctly, and if you accept changing the
output of (combinations [[1 2]]) to ((1) (2)) instead of (1 2), which
I think makes more sense,then the reduce function does the job in one
line for you.

(defn combinations [items]
  (reduce #(for [l % i %2] (conj l i)) [[]] items))

the same, wordier and maybe clearer:

(defn combinations [items]
  (reduce (fn [output item] (for [o output i item] (conj o i))) [[]]
items))

and if you really need the output to be a list of lists instead of a
list of vectors, maybe something like:

(defn combinations [items]
  (map seq (reduce #(for [o % i %2] (conj o i)) [[]] items)))

Btw, I learned an awful lot about compact ways of doing stuff in
Clojure by doing the exercises (and checking others' solutions) on
4clojure.com, which I warmly recommend.

Nico


On Feb 27, 3:45 am, Mike Ledoux <mike.led...@gmail.com> wrote:
> So I recently decided to start learning Clojure.  I installed Clojure
> box and wrote this little method to compute all possible combinations
> of input:
>
>  (defn combinations [items]
>         (if (== (count items) 1)
>             (flatten items)
>             (for [frstitems (flatten (first items))
>                   tlitm (combinations (rest items))]
>                   (flatten (list frstitems tlitm)))))
>
> so (combinations [[1 2] [1 2]])
>
> returns
>
> ((1 1) (1 2) (2 1) (2 2))
>
> Is there a way I can get rid of the if form?  Having the if statement
> duplicates what the for loop does when it creates frstitems.  I tried
> removing the if statement so the function looks like:
>
>  (defn combinations [items]
>             (for [frstitems (flatten (first items))
>                   tlitm (combinations (rest items))]
>                   (flatten (list frstitems tlitm))))
>
> but when I do this the function just returns an empty list.  I tried
> to figure out why using the REPL but did not discover the problem.
>
> Is what I'm asking possible and if so what would the function look
> like?   Thank you.
>
> So far Clojure is pretty cool!
>
> Mike

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to