Wednesday, December 01, 2021

Getting Started with Clojure - Quick Tutorial

How to run a clojure file from terminal?

 clj /tmp/my.clj


How Clojure to read from stdin?

(print (read-line))


How to pass a file through stdin to a Clojure program from terminal?

cat /tmp/input.txt | clj /tmp/my.clj


How to hello world in Clojure?

(print "hello")

How to read all lines from stdin? (assuming less than 500 lines)

(print (take-while some? (repeatedly 500 #(read-line) )))

How to define a variable? (a variable that doesn't change.. ok! a constant! )

(def n (read-line))

How to parse string in stdin to an integer?

(def n (Integer/parseInt (read-line)))


How to map a lambda function on a list?

(map count ["hello", "world"])


(map #(count %) ["hello", "world"])


How to map a lambda function on a list, and do many things with each item?


(map #(do (print "hello") (count %))  ["hello", "world"])


How to print hello 3 times?


(map println (repeat 3 "hello"))



How to get an element in a list?


(get ["hello", "world"] 1)


How to zip two lists? - concat two lists


(map vector [1 2 3] [4 5 6])


How to create a hashmap for look up?


(def lookup (zipmap [1 2 3] [4 5 6]))


How to get a value from a hashmap by key? - same as getting an element in a list

(get lookup 3)



How to define a function?


(defn add [a b] (+ a b))




No comments: