Thursday, 26 July 2012

Clojure revisit

Well, it appears i've forgotton all my clojure knowledge. The only thing I appear to have remembered is the thinking style behind it all. So, after reviewing some basics today let's write them down.

Getting to the REPL

java -cp clojure-1.4.0.jar clojure.main

Basic Math

(+ 1 2 3)
(- 3 2 1)
(/ 1 2 3)
(* 1 2 3)

Numbers

Numbers can be represented infinitely appended with an M or as ratio's.
2r10110110 ; this is radix 2 (bin)
8r755 ; this is radix 8 (oct)
16rFFF ; this is radix 16 (hex)

Types

There are many forms of types available in clojure
nil ; equivalent to null essentially, it is neither true or false
true false ; these are boolean values :fred ; this is a symbol
\c \newline \space \tab ; these are chars
"string" ; this is a string literal
(1 2 3) ; this is a list
[1 2 3] ; this is a vector
{:a 1 :b 2 :c 3} ; this is a map
#{:a :b :c} ; this is a set
^{:a 1}[1 2 3] ; this is a vector with metadata

Functions

Functions are defined with the fn function, however this creates anonymous functions and to store them you need to use defn
(defn average [x y] (/ (+ x y) 2))

Useful functions

Just some I remember from last time

  • (zipmap [:a :b :c] [1 2 3])
    {:c 3, :b 2, :a 1}
  • (doc zipmap)
    ; prints current documentation
  • (source zipmap)
    ; prints source
  • (cons :y [:a :b :c])
    [:y :a :b :c]

In my next post about clojure I want to include some stuff about map, reduce and filter.

No comments:

Post a Comment