Am 17.01.2012 22:17, schrieb Cedric Greevey: > On Tue, Jan 17, 2012 at 3:46 PM, Dennis Haupt <d.haup...@googlemail.com> > wrote: >> after the "wtf"s have worn off a bit, go on reading. >> imagine a simple problem: you have a collection of numbers and you have >> to write a function which collects all the numbers that are contained >> uneven times. for example, for a collection (1,2,3,2,3,4) the correct >> result is (1,4) >> >> ask a child: >> "you just make pairs and return the leftovers" >> >> ask a non-child human: >> "count how often a number is in the list and pick the ones that are >> contained uneven times" >> >> i also asked some oo programmers. one of the answers involved a >> multimap, building it, iterating over it again and putting the result in >> a new list. one answer was "i don't see any purpose in this". >> there was no FP coder around at that time. > > FWIW, > > (defn odd-occurrences [x] > (map first > (filter > (fn [[_ v]] (odd? v)) > (frequencies x)))) > > Signed, > An FP coder > > :) >
it's interesting that the FP solutions translate almost 1:1 to the explained task //non child's solution def odds(numbers:Seq[Int]) = numbers.distinct.filter(e => numbers.count(_ == e) % 2 =! 0) //child's solution - more efficient def oddsViaFold(numbers: Seq[Int]) = { numbers.foldLeft(HashSet.empty[Int])((acc, e) => { // store those which are waiting for a second number in a set if (acc.contains(e)) acc - e else acc + e }) } -- -- 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