Skip to content

Instantly share code, notes, and snippets.

@ujihisa
Created November 12, 2013 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ujihisa/7423626 to your computer and use it in GitHub Desktop.
Save ujihisa/7423626 to your computer and use it in GitHub Desktop.

From Ruby to Clojure

From Ruby to Clojure

Introduction

  • No advanced topics
  • For newbies

Clojure

  • imperative
  • S-Expression
  • anti object-oriented

programming language

  • on JVM
  • on JavaScript

Hello world

(prn "hello world!")

Hello world (2)

(def hello-world "Bonjour!")

(defn -main []
  (prn hello-world))

Use functions

Examples in Ruby and JS to show differences

  • Ruby
p (x + 10) * 2
  • JavaScript
console.log((x + 10) * 2);
  • Clojure
(prn (* (+ x 10) 2))
  • Or
(prn (-> (+ x 10) (* 2)))

Lambda

Ruby

-> (x) {
  (x + 10) * 2
}

JavaScript

(function(x) {
  return (x + 10) * 2;
})

Clojure

(fn [x]
  (* (+ x 10) 2))
  • Or with macro
#(* (+ % 10) 2)

CM

(CM)

Quick summary

(def hello-world "hi!")

(defn -main []
  (prn hello-world))

(fn [x]
  (* (+ x 10) 2))
; same
#(* (+ % 10) 2)

Other data structures

  • Symbol :abc

  • Vector

[1 2 3 4 5]
["a" :b \c]
  • List
'(1 2 3)
(list 1 2 3)
(cons 1 (cons 2 (cons 3 nil)))

(conj (conj (conj nil 3) 2) 1)
(conj nil 3 2 1)
  • Map (dictionary; hash)
{:a "hi" :b []}

Good

easy to

  • read
    • macro / immutability / naming
  • write
    • syntax
  • make it concurrent
    • immutability / future / STM

Good naming

  • defn/fn
  • prn
  • cons/conj
(cons 1 [2 3]) ;=> [1 2 3]
(conj [2 3] 1) ;=> [2 3 1]

Good naming

(if a
  b
  c)

(if a
  (do
    b1
    b2)
  c)

(when a
  b1
  c2)

Comment

  • comment + expr
  • #_ + expr
  • ; (linewise)
(prn #_(+ 2 (* 3 4)) 999)

JVM

  • Clojure is good partly because it's on JVM

  • Clojure is terribly bad because it's on JVM

JVM

  • Java
x.m(a, b);
C.f(x);
  • Clojure
(.m x a b)
(C/f x)

Performance

  • slow to start, fast to run

  • faster to start, slower to run compare to Scala

Performance

Ruby (2.1.0)

  • hello world: 0.02sec
  • fib(40): 15.58sec

Clojure (1.5.1)

  • hello world: 1.19sec
  • fib(40): 4.84sec

Practical?

Yes!

  • Leiningen (build tool)

  • clojars.org (library; ecosystem)

  • tools that depend on libraries for java

tricky parts

  • No continuations (call/cc)
  • No automatic tail call optimization
  • No alternative string literals
  • (No user-defined reader macro)

Summary

  • Clojure

  • made by Rich Hickey since 2007

  • google "tryclojure" to run some code even without installing clojure

  • From Ruby to Clojure

    • From Java to Ruby

Demo + Q&A

  • fib benchmarking (live coding)
  • make an app w/ leiningen
  • make a web app

references

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment