Higher Order Blog

home

Clojure without the parentheses: looks a bit like ruby :)

31 Aug 2010

I gave an introductory talk about Clojure at Trifork yesterday: https://secure.trifork.com/aarhus-2010/freeevent/index.jsp?eventOID=2713 I really wanted to focus on the core of Clojure: things like time/state management, functional programming, programming to contracts, meta programming, host interop, dynamics, interactivity and expressive power. I want people to see what Clojure is without being blinded by what is a mental blocker for some: the parentheses. So as a fun exercise, I decided to remove (almost) all parentheses from code on my slides. As it turns out, the code looks much like ruby or python (just more functional and concise). All code on my slides can be turned into real Clojure code by inserting parens appropriate places (newlines and indentation help with "visual parsing"). The "commas are whitespace" is used to make it more readable (for comma-liking eyes). Obviously as we go into meta programming with macros this breaks down, but that is the last topic of the talk :) slides Github repos: http://github.com/krukow/swing-demo http://github.com/krukow/ants-demo http://github.com/krukow/clojure-circuit-breaker Examples (I know the semantics aren't exactly the same, but I am considering syntax here).
Ruby:
ruby-1.9.2-p0 > def m
ruby-1.9.2-p0 ?>  {:name => "Karl", :age => 42}
ruby-1.9.2-p0 ?>  end
ruby-1.9.2-p0 > m
 => {:name=>"Karl", :age=>42} 
ruby-1.9.2-p0 > 

Clojure:
user> def p
         {:name "Fred", :age 42}
#'user/p
user> p
{:name "Fred", :age 42}

Ruby:
ruby-1.9.2-p0 > class Person
ruby-1.9.2-p0 ?>  attr :name,:age
ruby-1.9.2-p0 ?>  attr_writer :name,:age
ruby-1.9.2-p0 ?>  end
ruby-1.9.2-p0 > p = Person.new
 => # 
ruby-1.9.2-p0 > p.name="fred";p.age=42;
ruby-1.9.2-p0 > [p,p,p].map &:name
 => ["fred", "fred", "fred"] 

Clojure:

user> map :name [p,p,p]
("Fred" "Fred" "Fred")
;;or
user> defrecord Person [name,age]
user.Person
user> def p 
         Person. "Fred", 42
#'user/p
user> map :name [p, p, p]
("Fred" "Fred" "Fred")

Ruby:
ruby-1.9.2-p0 > [p,p,p].map(&:age).reduce(&:+)
 => 126 

Clojure:

reduce + 
   map :age [p p p] => 126
;;or
->> [p p p] 
          map :age
           reduce +