Orbit in Clojure 34

Posted by Uncle Bob Wed, 02 Jun 2010 22:08:56 GMT

I spent the last two days (in between the usual BS) writing a simple orbital simulator in Clojure using Java interop with Swing. This was a very pleasant experience, and I like the way the code turned out – even the swing code!

You can see the source code here

Those of you who are experienced with Clojure, I’d like your opinion on my use of namespaces and modules and other issues of style.

Those of you who are not experienced with Clojure, should start. You might want to use this application as a tutorial.

And just have fun watching the simulation of the coalescence of an accretion disk around a newly formed star.

Comments

Leave a response

  1. Avatar
    anonymous about 12 hours later:

    Code is hard to read since it is not using idiomatic lisp/clojure style. Please don’t put closing parens/braces on new line, since it is not readable. Use indentation to distinguish code blocks instead. If you are not suer about indentation, just use emacs clojure-mode defaults which does quite a good job at is.

    Sorry, but this is real blocker and makes code painful to read, so I can’t comment on the code itself.

  2. Avatar
    Julian Birch about 15 hours later:

    Being a C# programmer, I don’t really have a problem with the parens. I’d probably use map and filter more in the physics code. e.g. (defn accelerate-all [os] (map accelerate os)) At that point, you probably don’t need the function at all. That’s true of pretty much all of the -all functions except collide-all.

    Don’t know if you care about this, but I think collide-all might have an edge case: when three objects collide simultaneously, I think it goes wrong. (Sorry, no repl handy to check this…)

    Oh yes, and I’d call “vector” vector2d. :)

  3. Avatar
    Steve about 16 hours later:

    Not a single comment, so much for clean code.

  4. Avatar
    Derrick Spell about 17 hours later:

    haha … everyone seems so testy today.

    I’ve never looked at Clojure code before, but a cursory glance at this and I can see the basic structure. Seems like formatting is very readable. Even without a working knowledge of Clojure I can follow along without comments.

    I look forward to digging in a little closer after work tonight!

  5. Avatar
    klang about 18 hours later:

    Leiningen support is nice to have .. it makes life easier, so I forked and added that convenience.

  6. Avatar
    Chris Vest 1 day later:

    I forked the lein support repo and took a late-night stab at the indenting. Not that I claim my indenting is idiomatic, but it’s probably closer.

  7. Avatar
    Julian Birch 1 day later:

    I couldn’t leave collide-all alone, so here’s another version: first, observe that collide? is reflexive and symmetric but not necessarily transitive. But for collisions, we want it to be transitive. So, we need a function group-by-nontransitive-relation. Then all we need to do is merge the results together.

    A function like this should do that

    (defn merge-all [should-merge?, merge, coll] 
        (map
            (partial reduce merge)
            (group-by-nontransitive-relation should-merge? coll)))
    
    and then collide-all becomes
    (defn collide-all [coll]
        (merge-all collides? collide coll))
    

    Finally, I need to write the group by function. So, I can use a hashmap to do the grouping, using the key as the first element that is part of the collision and values as the objects that will collide. (We throw away the keys at the end with a call to vals.) Since we’re iterating through a list and producing a result, reduce is the way to go.

    I can’t come up with a simpler way of expressing it than this, which annoys me:
    ; Couple of observations
    ; hashMap in this code is a hashmap whose values are lists  Dictionary<T, List<T>> in C#
    ; In particular, (second %) is the second element in the hashMap sequence, and so is a list itself
    ; Worst case scenario is when the item encountered matches multiple sets.  Then the sets need to be merged
    (defn group-by-nontransitive-relation [related?, coll]
        "Returns a sequence of sequences, corresponding to the equivalence groupings specified by the non-transitive relation 'related?'." 
        (letfn [
            (isMatch [coll, o] (some (partial related? o) coll))
            (find-matching-groups [hashMap, o] (filter #(-> % second (isMatch o)) hashMap))
            (add-groups-to-lookup [hashMap, o, groups]
                (assoc 
                    (reduce dissoc hashMap (map first groups)) 
                    (ffirst groups) 
                    (conj (reduce concat (map second groups)) o))) ; Merge the equivalence sets
            (add-to-lookup [hashMap, o] (if-let 
                [matching-groups (not-empty (find-matching-groups hashMap o))]
                (add-groups-to-lookup hashMap o matching-groups)
                    ; add to the current key's values
                (assoc hashMap o [o])))]
                    ; new key with only one entry
            ; Creates a hashmap of related objects keyed by the first element in the equivalence class
            ; Then just throws the keys away with a call to "vals" 
        (vals (reduce add-to-lookup '{} coll))))
    
    A quick test you can run in the repl:
    (defn is-close? [x y] (or (= x (inc y)) (= y (inc x))))
    (merge-all is-close? + [1 3 5 6 10 2 12])
    
    This should return (6, 11, 10, 12), in no particular order.
  8. Avatar
    Julian Birch 1 day later:

    Couple of extra observations: turns out that defining the inner functions within add-to-lookup appears to be significantly faster. Of course, inlining completely is faster as well, but not to an extent you’d expect.

    Sadly, whatever you do, the performance is bad. You can fix this by breaking the algorithm slightly: only checking the keys rather than all the values, which in turn simplifies add-groups-to-lookup. This doesn’t quite get the right answer, but it conserves mass and would probably not be noticeable in practice. (merge-all is-close? 1 3 2) would return (3 3) or (1 5) instead of (6).

  9. Avatar
    p90x workout 5 days later:

    P90X workout programe is designed to transform your body and makes you keep fit and strong. And P90X system, an advanced training technique, can accelerates the results process without feeling boring. The programe Beachbody dvd would provide you with the ultimate in at-home fitness.

  10. Avatar
    MKV to iPad 5 days later:

    iPad Video Converter aupports users to customize output videos for better image quality. No matter you are a profession or not, you are supposed to be a profession to adjust video and audio quality to get whatever you want.

  11. Avatar
    Pawel Badenski 6 days later:
    @Derrick Spell

    It’s not about testiness. Research shows that “advanced programmers have strong expectations about what programs should look like, and when those expectations are violated their performance drops drastically” [Empirical studies of programming knowledge, E. Soloway and K. Ehrlich]. Needless to say they outperform novices on familiarly “constructed” codebases.

  12. Avatar
    p90x workout 12 days later:

    P90X is a working out system includs P90X workout and Insanity DVD which belong to P90X fitness program.

  13. Avatar
    Tommy McGuire 13 days later:

    @Julian Birch Your final merge-all example would be clearer if you used list instead of +:

    (merge-all is-close? list [1 3 5 6 10 2 12])

    produces something like (12 ((2 3) 1) 10 (5 6)).

  14. Avatar
    ceramic lamp 22 days later:

    Thanks for a great time visiting your site. Pretty good post. I just stumbled upon your blog and wanted to say that I have really

  15. Avatar
    cell phone headset 26 days later:

    Nice one. I have stumbled and twittered this for my friends. Hope others find it as interesting as I did.

  16. Avatar
    cell phone headset 26 days later:

    Nice one. I have stumbled and twittered this for my friends. Hope others find it as interesting as I did.

  17. Avatar
    pump shoes 26 days later:

    It seems that you have set many work in to your article and We require more of

    those about the net presently. I truly got a drag out of one’s article. We do not

    actually possess a lot in order to communicate reacting, I just wished to comment

    in order to respond incredible perform

  18. Avatar
    pump shoes 26 days later:

    It seems that you have set many work in to your article and We require more of

    those about the net presently. I truly got a drag out of one’s article. We do not

    actually possess a lot in order to communicate reacting, I just wished to comment

    in order to respond incredible perform

  19. Avatar
    MBT Chapa 26 days later:

    interesting i am definatley going to look further into this.

  20. Avatar
    movies 29 days later:

    thanks for code source – http://github.com/unclebob/clojureOrbit

  21. Avatar
    http://www.laviesolar.com about 1 month later:

    Hello and many greets from China ! Nice design.Looks so comfortable. Many thanks for the wonderful site and the opportunity to say hello.

  22. Avatar
    Olivea Copper about 1 month later:

    Three blonde women were stranded on an island. While trying to dig their way out, one of them came across a buried lamp. Suddenly a genie appears and offers to grant each one of them one wish, in return for saving him.

  23. Avatar
    If you want to purchase the <a href="http://www.p90x-buying.com">P90X Extreme Home Fitness</a> System for yourself, the best place to begin is online. Many Internet sites-such as http://www.p90x-buying.com, for example-have great pricing($59.99) and shi about 1 month later:

    If you want to purchase the P90X Extreme Home Fitness System for yourself, the best place

    to begin is online. Many Internet sites-such as http://www.p90x-buying.com, for example-have great pricing($59.99) and shipping

    discounts, as well. Even with the shipping cost, you could end up paying less than you would in a local store.

  24. Avatar
    If you want to purchase the <a href="http://www.p90x-buying.com">P90X Extreme Home Fitness</a> System for yourself, the best place to begin is online. Many Internet sites-such as http://www.p90x-buying.com, for example-have great pricing($59.99) and shi about 1 month later:

    If you want to purchase the P90X Extreme Home Fitness System for yourself, the best place

    to begin is online. Many Internet sites-such as http://www.p90x-buying.com, for example-have great pricing($59.99) and shipping

    discounts, as well. Even with the shipping cost, you could end up paying less than you would in a local store.

  25. Avatar
    p90x dvds about 1 month later:

    If you want to purchase the P90X Extreme Home Fitness System for yourself, the best place

    to begin is online. Many Internet sites-such as http://www.p90x-buying.com, for example-have great pricing($59.99) and shipping

    discounts, as well. Even with the shipping cost, you could end up paying less than you would in a local store.

  26. Avatar
    Peasant blouse about 1 month later:

    using qualitative produce elegant light spins the romantic sense, plus the broken this year popular element , presents different female glamour.

  27. Avatar
    Sheath dress about 1 month later:

    Sunshine of summer, the beautiful flower asperses full whole body, sweet and elegant breath, the circulation of the spread of elegant silk dress eyes from the waves to linger flying skirt . A gentle and graceful elasticity waist foil, more show delicate temperament of your daughter beauties.

  28. Avatar
    jingjia about 1 month later:

    iPhone Ringtone Custom turns your dream of making your own iPhone/iPhone 3G Ringtone with loved music into reality in the way of converting almost all mainstream video/audio format to M4R iPhone ringtone, such as avi, mpeg, mp4, mov, flv, mp3, aac, m4a, wma, etc. to M4R iPhone Ringtone, even rip DVD Disc to Ringtones for iPhone. Convert to iPhone Ringtone Change iPhone Ringtone Convert Music to iPhone Ringtone Convert MP3 iPhone Ringtone Convert M4A to M4R Convert MP4 to iPhone Ringtone

  29. Avatar
    liveyou 2 months later:
  30. Avatar
    cosplay 2 months later:

    Hello and many greets from China ! Nice design.Looks so comfortable. Many thanks for the wonderful site and the opportunity to say hello.

  31. Avatar
    supplynflshop 3 months later:

    thanks for sharing

  32. Avatar
    JetsShop 3 months later:

    Thank you for post this comment there have same you like to chose Jets Jerseys

  33. Avatar
    coachoutlet 3 months later:
    Today, Coach has developed into a global brand, offers a variety of decorative assembly line of men and women.Our coach outlet include handbags, shoes, watches, outdoor clothing, scarves, sunglasses, jewelry and perfume series coach bags.Welcome to see coach brooke collection .

    http://www.coachoutletnew.com

  34. Avatar
    UGG Bottes 3 months later:

    Tout d’accord sur votre opinion. Et moi, aussi le fan de bottes uggs, surtout sur sa doublure en laine. La marque ugg bottes. venait de trouver sa signature. En ce moment, vous pouvez pré-commander les UGG Pas Cher!

Comments