Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>you can almost write the actual code just the pseudo code.

Yes, often true. E.g. in this case:

  (->> [2 3 4 7 5 3 11 12 7] ;collection
     (group-by even?)        ;get a map of evens and odds
     vals                    ;get just the values
     (map sort)              ;sort them
     (map first))            ;first is smallest
(disclaimer: there's probably prettier ways to write this - I was just trying to keep it simple)

I agree that there are sometimes inscrutable errors. For me it's often because of a type conflict between a function and what it's operating on.

Example: I'm a little rusty and when I tried to quickly code the example above I did this:

  (->> [2 7 5 3] (partition-by even?) vals)
And got:

  ClassCastException clojure.lang.Cons cannot be cast to java.util.Map$Entry  clojure.lang.APersistentMap$KeySeq.first (APersistentMap.java:152)
Doh! I wanted "group-by". And partition-by doesn't make a map! But why this specific error? Frankly I'm not sure. I'd probably have to look at the source. My sin of course was trying to compose operations in one go, rather than build them up by baby steps in the REPL. I don't think the errors ever get that much more readable, but you start to recognize the category of error you've made by the type of error that's thrown.

Spending time on 4Clojure is very helpful to build your intuition for this.



You can make that somewhat more close to the correct computation, you don't need to sort the lists, you just need min values.

  (->> [2 3 4 7 5 3 11 12 7]
       (group-by even?)
       vals
       (map #(apply min %)))</pre>
However, operation like this can be made much more readable if you actually use variables like this:

  (defn min-even-odd [xs] 
    (let [evens (filter even? xs)
          odds (filter odd? xs)] 
       (list (apply min evens) (apply min odds))))

  (min-even-odd [2 3 4 7 5 3 11 12 7])
Which is a bit longer, but I think it makes more sense.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: