Clojure From a Rubyist Perspective
- August 15th, 2012
- Posted in Clojure
- By Michael Blake
- Write comment
I like to preach language agnosticism, I believe in it with a religious fervor. But the truth is I do Ruby, I’ve done Ruby for a long time and I’m comfortable in it. It’s a structure I understand, I know the libraries the features and the communities.
So it’s time to kick myself in the ass and get on the Clojure train before it leaves the station, because I don’t want to be that guy who just knows Ruby.
In the nature of my blog, I ramble too much and it’s a good idea for me to split this into functional segments that will make sense without overwhelming.
This is part one of my take on clojure, and let me tell you, it’s a little bit scary!
Hello Clojure!
Like most people setting out into the scary and unknown world of a new programming language, I judge a lot (too much, usually) based off of the Hello World statement. So let’s see what Clojure has to offer there!
Let’s start at the basics. Clojure is functional much like Ruby is OO. Meaning obsessively so. In Clojure you think, breathe and live functions. So hello world itself puts us straight into that mindset. We’re going to declare a function.
user=>(def sayHi (fn [] "Hello Clojure")) #user/sayHi user=>(sayHi) "Hello Clojure"
Well that was easy! We’ve defined a function and it’s returning Hello Clojure. My first thought? That’s a lot of stuff to say hello, and we’re not even printing it. Let’s clean that up a little using the defn macro that Clojure provides us.
user=>(defn sayHi [] "Hello Clojure") #'user/sayHi user=> (sayHi) "Hello Clojure"
That’s much better. We removed a set of unnecessary parens and made it easier to read. It’s still verbose if I were to compare it to Ruby’s Hello World, but if you think about it functionally it’s not just hello world, you’ve actually defined a reusable function that provides you the message you want to print. In Ruby that would (usually) look something like this.
def sayHi "Hello Ruby" end
That’s something you could turn into one line, but it wouldn’t make it any easier to read. Functional programming forces you to define something that can be used again and again, and that’s just saying hello.
Next time, we might have make a web page.
No comments yet.