Fibonacci
(def fib-seq
(lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))
Powers of two
(def twopowers (lazy-seq (cons 1N (map #(* 2N %) twopowers))))
Factorial
(def fact (lazy-cat [1N] (map * (map #(+ % 2) (range)) fact)))
I decided to learn a functional language: I chose Clojure, because it runs on the JVM, and it seems more easy to digest for me, having some Java background. In this blog, I am going to write notes mainly for myself. However, since I already take the time to write them down, why not publish them? Maybe they will be useful for someone else too :) Please keep in mind, that I'm an absolute beginner in Clojure. So please use my blog only at your own responsibility. You have been warned ;)
(def fib-seq
(lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))
(def twopowers (lazy-seq (cons 1N (map #(* 2N %) twopowers))))
(def fact (lazy-cat [1N] (map * (map #(+ % 2) (range)) fact)))
println.
(with-out-str (println "Hello")) ; result "Hello\n"
(conj m (when value [key value]))
Usage example:
(conj {
:type "if"
:cond cond_val
:then then_val
} (when else_val [:else else_val]))
In the above example, the "else"-part is added to the token only if it is not empty.
Source.Clojure> (assoc [1 2 3] 1 5) [1 5 3]
Usage example:
(defn dialogue[num]
(let [dacode (map #(- (int %) 48) (Integer/toString num 2))
phrases [(s/split"It would be extremely painful... for you!"#" ")
(s/split"If I pull that off will you die? You're a big guy."#" ")]
actors ["BANE" "CIA"]]
(loop [idxs [0 0] finaldial "" code dacode prevbit 2]
(if (< (count code) 1) finaldial
(let [bit (first code) idx (idxs bit)]
(recur (assoc idxs bit (inc idx)) (str finaldial (if (= bit prevbit) " " (str (when (not= 2 prevbit) "\n")
(actors bit) ": ")) ((phrases bit) idx)) (rest code) bit))))))
Important part:
(assoc idxs bit (inc idx))
In this example there are two counters, stored in idxs vector (initially 0, 0). In each step we update one of the two, indexed by bit
Source.