London ClojureBridge Event as Teaching Assistant

Clojurebridge experience as teaching assistant

I have been learning Clojure/ClojureScript over the last three months in my spare time. I felt lucky to be asked to volunteer to be a teaching assistant for the ClojureBridge event held at USwitch on the 19th and 20th Feb 2016.
I was feeling apprehensive initially due to my limited exposure to a functional programming language and most of the teachers and teaching assistants were either working full time with Clojure or had several years of playing with Clojure and were using a Mac while I have used Windows laptop to play with Clojure. The environment was friendly and everyone was ready to help each other making everyone feel welcome.

Clojurebridge is an event aimed for people identifying themselves as female or nonbinary with the purpose of introducing Clojure and  widening the Clojure community. The event was sponsored by USwitch and Shutl mainly and made possible with the 6 teachers and several teaching assistants giving their Friday evening and Saturday to the community happily. Some of the attendees with some experience in Clojure decided to be a teaching assistant instead of being a student on the day. Our roles were versatile.

I am still settling in my new job I started this month working longer hours to get comfortable with the different technologies used. which didn’t leave much time to prepare additional material for the event. I did a talk sharing my experience about learning Clojure at London Clojurians Group beginning of this month
https://skillsmatter.com/skillscasts/7531-experience-learning-clojurescript.

I was thinking of building something fun may be a game to inspire the audience to start playing for Clojure but did not have enough time to build anything. I spent the time familiarising and working through the exercises of the ClojureBridge curriculum to get ready for the event
http://clojurebridge.github.io/curriculum/#/

Since I have experience using Clojure on a Windows laptop, I was helping mostly students having windows to install the tools needed for the ClojureBridge event, i.e. leininghen, lightable, github (to pull clojure projects from github) and java jdk during the install fest on Friday evening to get the CLojure setup for Saturday. There were around 25 attendees trying to download the software around the same time causing the internet connection to drop several times slowing the download for the student I was trying to help.

We were pampered with pizzas, salad and beers which were welcome especially after a long day at work on Friday evening. The organisers, Denise Yu, Chris Howe-Jones, John Stevenson and others made sure we have tasty healthy food and drinks to keep going. For breakfast, bagels with different fillings, pastries, coffee and juice were provided. Much to our delight, we had chinese food for lunch followed by ClojureBridge cookies which I was reluctant to eat because they look perfect.

IMG_20160220_131502

We started Saturday morning with lightning talks by John Stevenson, Philip Potter and Chris Ford (live music code compiling @ http://ctford.github.io/klangmeister/).

CbpjSWKW0AAxL2y
The attendees were divided into three categories: new to programming, developers with no experience with Clojure and adventurous developers with some knowledge of Clojure. Teachers and teaching assistants picked the level of groups they were willing to teach. I picked the group with no programming experience. I was the teaching assistant and Waldemar Schwan was the teacher. He has done a brillant job teaching by using examples and the girls in our group were soon enthused to ask questions.

Cbpv4M8W0AAinX6

The newer version of LighTable 0.8.1 does not have the instarepl and the curriculum still has reference to instarepl. Waldemar was ingenious to suggest using a new file (.clj) to write code and evaluate line by line. The advantage was the student could save their work and evaluate only lines they wanted to run. Unfortunately LightTable seem to crash randomly on the attendees’ laptop and my classic solution was to close and reopen LightTable. Almost all attendees have a Mac with a few exceptions who had Windows. The UI of lightTable is similar with different keys to perform different actions.

The girls were amazing and were adventurous enough to go beyond the exercise. They tried to do a S shape and K shape with the Walk the Turtle exercise. (S and K are initials of two of the attendees) and one went on to create her extended family tree using map of maps. The inherent use of parentheses seem a hard to get used to but they would instantly correct it if their line of code does not run. The terminology was confusing one of the attendee thought vector was a list while list is a different data collection which was not mentioned in the curriculum. We got asked questions regarding immutability of data and tried our best to explain the power of immutable data collections. However it was harder to explain mutability of the atom and how it works well with immutable data collections to maintain states of an application.

The morning went smoothly and the afternoon I felt the attendees needed some time to process whatever was covered in the morning to continue with more concepts.
We finished the day with a retrospective so as we can get the feedback of the attendees to help improve the event in the future. Everyone seem to have enjoyed the event. Some wanted it to last longer while others wanted it to be shorter.IMG_20160220_165701

Advertisements

Clojure loop: doseq,dotimes, while, loop, recur

In Clojure loop can be performed using doseq, dotimes, while,loop, loop/recur and defn/recur functions.

doseq
doseq function iterates over a sequence performing something against each element. It is similar to foreach in C#.

doseq forces evaluation for a lazy sequence

doseq

(doseq [n (range 3)] ;;binding each value from the seq to n
(println n))

Result : (0 1 2)

dotimes
dotimes function evaluates same expression n times similar to for loop in C#.
dotimes takes a name and a value vector and performs the expression inside of it number of times based on value passed.

(dotimes [i 3]
(println i))

dotimes

while
while function in clojure is similar to while in C#.
while continues evaluating the body as long as the condition is true

(def a (atom 10))
(while (< 0 @a)  (do (println @a) (swap! a dec)))

while.JPG

In the above example, an atom with initial value of 10 is created and assigned to symbol a.

Atoms provide a way to manage shared, synchronous, independent state. They are a reference type like refs, i.e, points to a value.
The swap function updates the value of the atom.

The dec function substracts 1 from the atom value.

The while is executed until the atom a value is no longer less than 0.

loop/recur
loop/recur takes a binding vector and a condition is defined and recur is used to re-execute loop with new bindings.

(loop [i 0]

(if(< i 10)
(recur (inc i))  i))

In the example above loop initialises  i down to 0 and iteratively increments by 1 with the help of recur until i is 10.

loop

defn/recur
defn/recur can act as loop expressions in the sense that a recur inside the function is meaningful and results in the functions being called again with new bindings as specified by recur.

(defn increase [i]
(if(< i 10)
(recur (inc i))
i))
(increase 1)

defnRecur

In above example, the loop from previous example is defined into a named function increase that takes a single argument. if a number less than 10 is passed, increase will loop some number of times and return i until 10 is reached.

An example how the defn/recur  is useful is the factorial function found from

http://stackoverflow.com/questions/1662336/clojure-simple-factorial-causes-stack-overflow

(defn fact[x] (if (<= x 1) 1 (* x (fact (- x 1)) )))

(fact 1000) ;; throws arithmeticException integer overflow

ArithmeticOverflow.JPG

The factorial function breaks with integer overflow with 1000.

The combination of defn/recur can be used to prevent the error

Clojure uses the tail-call optimisation so that the overflow does not occur

def_recur.JPG

(defn factorial ([x] (factorial 1 x))
([accum x]
(if (<= x 1) accum
(recur(*' accum x)(- x 1)))))
(factorial 1)

Clojure If, cond, case

Clojure has lots of operators for dealing with conditional statements: if, cond, condp, case and when.

Each of these is useful for different situations. Let’s take a look at them in turn:

if

if expression in Clojure returns a value similar to ternary operator in c# compared to a statement

The ternary expression in C# using the ? operator as follows

remark = (rating>10) ? "positive":"negative"

The expression is evaluated, if it is true the “then” part is executed and result returned otherwise the “else” part is  run and returned.

In Clojure the syntax is

if( condition
value-if-true
value-if-false)

In Clojure if on false and nil return false and the rest return true. A sequence on empty collection returns nil , thus falsey.

Syntax Definition Result
(if true :truthy :falsey) truthy
(if (Object) :truthy : falsey) ; objects are true truthy
(if [] :truthy : falsey); empty collections are true truthy
(if false  :truthy  :falsey)  falsey
(if nil :truthy :falsey)  nil is false falsey
(if (seq []):truthy :falsey); seq on empty collection is false falsey

The “else” in clojure if is optional

Syntax Definition Result
if(even? 6) “even” “odd”)  if expression with “else” part even
if(even? 6) “even”)   if expression without “else” part even
if(even? 7) “even”)   if expression without “else” part but evaluates to false. nil

if/do
The do operator allows to wrap multiple expressions per branch in each of the if branch. The last value of the expression is returned.

(if (even? 5)
(do (println "even") "not odd")
(do (println "odd") "not even"))

OddNotEven

In the above example odd in printed in REPL and “not even” is returned as the value of the if operation.

when

The when operator is like a combination of if  and do but with no else branch. For example

(when true (println “true”))

when.JPG

if-let
if-let is useful when the result is needed

(defn filter-evens [coll]
(if-let [evens (seq (filter even? coll))]
(println (str "Evens are:" evens))
(println "No evens.")))

filter_Evens


(filter-evens [1 2 3 4])
;;Evens are : (2 4)
(filter-evens [1 3])
;;No evens

In above example, the result of applying even filter to the collection is bound to collection evens. Empty collections return true while empty sequences return false. The seq operator is used to convert the collection into a sequence object so that if none of the values in the collection are even, false is returned and else part is executed instead of true returned.

cond
Unlike if cond can take a series of tests. For each test , there needs to be an accompanying expression. If one test evaluates to true, the expression is returned
: else expression is optional and evaluated if none of the tests evaluate to true.
(let [x 5] ;;binds 5 to x
(cond
(< x 2) “x is less than 2”
(< x 10) “x is less than 10”

:else “x is greater than or equal to 10”))

cond

In above example,  the value 5 is bound to symbol x and a series of tests are applied with a corresponding return value. The number 5 met the test “(< x 10)” thus returning “x is less than 10”.

condp

condp is similar to cond except it takes a shared predicate (condition), instead of passing  test expressions, test values are passed.

(defn evaluate [x]
(condp > x
5 "x is less than 5"
10 "x is less than 10"
"x is greater than or equal to 10")) ;; default argument to condp without test value
(evaluate 9)
(evaluate 3)
(evaluate 120)

condp.JPG

case

case is similar to switch case in C# or  JavaScript. The expression corresponding to the value passed will be evaluated. A default expression can be specified without any test value if there is no matching clause for the value passed.

case.JPG

(defn value [x]
(case x
5 "x is 5"
10 "x is 10"
"x isn't 5 or 10"))
(value 11) ;;"x isn't 5 or 10"
(value 10);;"x is 10

Clojure Sequences

Sequences include data structure lists, vectors and lazy sequences.

Functions that can be used with sequences can be found using the clojure cheatsheet.

http://clojure.org/cheatsheet

Below are some examples using vectors and lists as sequences.

 Syntax  Definition  Result
 (seq ‘(1 2 3 4))  If collection is not empty, return seq object else nil  (1 2 3 4)
 (first [1 2 3 4])  returns the first element  1
 (rest {:a 1 :b 2 :c 3 :d 4})  returns a sequence of the rest of elements after first element  ([:b 2][:c 3][:d 4])
 (cons 1 ‘( 2 3 4))  returns a new sequence: first is 1, rest is coll  (1 2 3 4)

Lazy Sequences

Lazy Sequences are integral part of Clojure.

They are not actually data structures but are objects that contain function which return next item in the sequence.

Lazy sequences allow for gen­er­ated log­i­cal sequence which does­n’t have to exist in mem­o­ry. It makes it pos­si­ble to have infi­nite sequences which can be cached and used whenever needed.

Examples of functions used with lazy sequences are:

Syntax Definition Result
 (range)  generates lazy sequence of numbers infinitely (0 1 2 3 4 5…n)
 (range 3)  returns first three numbers from the sequence.  (0 1 2)
 (range 1 7 2)  returns numbers with increment of 2 starting from 1 and ending 7  (1 3 5)
 (range 1 4)  returns numbers starting at 1 and ending at 4  (1 2 3)
(take 4  (range))  take first 4 numbers  (0 1 2 3)
(drop 4 (range)) similar to Take except means discarding the first 4 items (4 5 6 7…n)
(iterate inc 5)  iterate returns a lazy sequence starting at 5 using the inc function (5 6 7 8 9 10 11 ….n)
(take 4 (iterate (partial * 2) 5)) starting at 5 using the  multiply operation 2. (5 10 20 40)
 (map #(* % %) [0 1 2 3])  map iterates through each element in the vector and calculate

the square of the number

 (0 1 4 9 )
 (filter even? (range)) filter takes some sequence and predicate and return sequence of elements

where predicate is true. The example returns all even numbers

 (0 2 4 6 8….n)
 (re-seq #”[aeiou]” “clojure”)  returns sequence of successive matches of pattern in string  (“o” “u” “e”)

An example of the application of the iterate function is to generate Fibonacci numbers.

Fibonacci returns where a number is found by adding up the two numbers before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth, i.e.  Xn = Xn-1 + Xn-2.

Let’s write it in clojure

  1. Start with vector [0 1] which is the starting Fibonacci sequence
  2. Generate a sequence of elements from this vector added to each other using the iterate function. Iterate takes the starting vector [1 0] and applies a function
    (iterate ([0 1])
  3.  Define the function with single argument to which [0 1] will be passed. Destructure the argument into symbols a and b. a contains 0 while b  contains 1.
    (iterate (fn [[a b]]
    [0 1]))
  4. Inside the function, return a vector which is the sequence of next element. first element of the vector is b which is one and the second element of vector is a +b which is 1 also.
    (iterate (fn  [[a b]]
    [b (+ a b)])
    [0 1]))

    Running above code in REPL produces the following sequence [0 1] [1 1] [1 2][2 3][3 5][5 8]……[n n]
    Iterate
  5. The first element of the vector returned needs to be returned
  6. The map function can be used to iterate over each vector and using function first , the first element of the vector can be extracted
    (map first
    (iterate (fn  [[a b]]
    [b (+ a b)])
    [0 1])))

    mapfirst
  7. Create a function to generate the Fibonacci which can be invoked
    (def fibs
    (map first
    (iterate (fn [[a b]]
    [b (+ a b)])
    [0 1])))

    ;;return first five Fibonacci numbers
    (take 5 fibs)
    ;;drop first five Fibonacci numbers and return the rest up to infinite
    (drop 5 fibs)

    Fibonacci
    (map inc (take 5 fibs))
    mapinc
    It returns the first 5 Fibonacci numbers added to 1

Other Functions  on Sequences

Syntax Definition Result
 (reduce + (range 4))  reduce iterately invoke the function + with every element of the sequence  6
  (reduce + 10 (range 4))  reduce retains the result of the previous indication and uses it as first

argument in subsequent function. Sum of the sequence + 10

 16
 (into #{} “hello”)   Into functions injects element of the sequence into a concrete data structure  #{\e \h \l \o}
 (into {} [[:x 1] [:y 2]])   pouring sequence of key value pairs into a map  {:x 1, :y 2}
( some {2 :b 3 :c} [1 nil 2 3])   some takes a predicate function and returns the first element of the

sequence for which the predicate function returns logical true.

Takes advantage of map being a function. Each element in the vector 1, nil, 2 and 3

is passed as argument to the map. True is returned when 2 is reached.

2 is a key in the map which returns the value b.

 b
 (interleave [:a :b :c :d :e] [1 2 3 4 5])  returns a seq of the first item in each coll, then the second etc.   (:a 1 :b 2 :c 3 :d 4 :e 5)
 (partition 3 [1 2 3 4 5 6 7 8 9])  returns sequence of lists of 3 items each.   ((1 2 3) (4 5 6) (7 8 9))
 (map vector [:a :b :c :d :e] [1 2 3 4 5])  returns sequence of vectors associating key from first coll with value

from second coll

  ([:a 1] [:b 2] [:c 3] [:d 4] [:e 5]
 (apply str (interpose \,”asdf”))  a series of functions are applied.

Interpose add the “,” to each letter in the string and returns a list

(\a \, \s \,\ d \,\ f \)

str joins the list of strings into one string.

 “a, s, d, f

 

Clojure Destructuring

Destructuring allows to extract values from datastructures and bind them to symbols without explicitly looping/traversing the datastructure. It allows concise and simple coding.

Sequential Destructuring

Provides vector of symbols to bind by position.
Syntax: [symbol another-symbol] [“value” “another-value”]
 (def listNumbers[7 8 9 10 11])
;;Bind a, b, c to first 3 values in stuff
(let [[a b c] listNumbers]
(list (+ a b) (+ b c)))

Result: (15,17)

SequentialDestructuring

It binds to nil if there’s no data, i.e. there are not enough items in the vector to bind to.

(let [[a b c d e f] listNumbers]
(list d e f))

Result : (10 11 nil)

Nil_Destructuring

In the above example there is no data at 6th position in ListNumbers collection to bind to f explaining the nil being returned.

& symbol can get “everything else” with value being a sequence

(def listNumbers[7 8 9 10 11])
(let [[a & others] listNumbers]
(list others))

Result : (8 9 10 11
&amp;_Others

_  symbol is used for values that can be discarded

First element is discarded in the example below

(def listNumbers[7 8 9 10 11])

(let [[_ & others] listNumbers]
(list others)))
)

Result : (8 9 10 11)

_ Discard

Associative Destructuring

Provides map of symbols to bind by key.
Syntax: {symbol :key, another-symbol :another-key} {:key “value” :another-key “another-value”}

(def m {:a 7 :b 4})
(let [{a :a, b :b} m]
[a b])

Result : [7 4]

AssociativeDestructuring

keys  are inferred from vector of symbols to bind

(def m {:a 7 :b 4})
(let [{:keys [a b]} m]
[a b])

Result : [7 4]

Keys_Map

If a key is not found in the map, the symbol is bound to nil.

(let [{:keys [a b c]} m]
[a b c])

Result: [7 4 nil]

Map_Nil

:or provides default values for missing keys with a map of values

(def m {:a 7 :b 4})
(let [{:keys [a b c]
:or {c 3}} m]
[a b c])

Result: [7 4 3]
Or_Map

Named Arguments 
Vector of keys can be bound to & to emulate optional named arguments.

(defn people [planet & {:keys [adults children]}]
(+ adults children))

(people “Earth” :adults 1 :children 5)

Result:6

NamedArguments

Clojure Immutable Collections

Clojure data is immutable. Values of simple data types are immutable , e.g. true, 4, 4.05.

With immutability values never change, instead new values are generated  when new states  are needed. It means all states of the collection can be referred throughout the life cycle of the application.

Advantages of immutability can be read from blog http://www.developer.com/lang/other/article.php/3874551/Clojure-Immutability-at-the-Language-Level.htm

Clojure provides several immutable collections listed below

Lists

Below are the syntax associated with lists

Syntax Definition Result
 ()  empty list
 (1 2 3)   1 is interpreted as a function and fails
 ‘(1 2 3)

or

(list 1 2 3)

The quote sign means don’t evaluate the list and is a macro for denoting list.  (1 2 3)
(conj ‘(1 2 3) 1) The conj add value 1 at beginning of list  (1 1 2 3 )

List_Data

lst returns (1 2 3) in the screenshot because  of immutability.

Vectors

Vector is similar to array object in other languages like C# and JavaScript

Syntax Definition Result
 []  empty vector  []
 [1 2 3]

(vector 1 2 3)

(vec ‘(1 2 3))

vector can be defined using the [] symbols

vector is a function to define a vector.

vec is a function to convert list into vector

 [1 2 3]
(nth [1 2 3] 0]  returns element at position 0  1
(conj [1 2 3]  1) add 3 to vector  [1 2 3 1]

Vector_data

Map

Maps is similar to dictionary object in C#. The values stored are unordered.

Syntax Definition Result
 {}  empty map
  {:a 1 :b 2} Map collection containing

a is a pointer to 1

b is a pointer to 2

   {:a 1 , :b 2}
(assoc  {:a 1 :b 2} :c 3)  associate key c with the map   {:c 3 , :a 1, :b 2 }
(dissoc {:a 1 :b 2} :a) dissociates key a from map  {:b 2}
(conj {:a 1 :b 2} [:a 1]) add vector key a to map    {:c 1 , :a 1, :b 2 }

Map_Data

Nested access to data in maps is possible using helper functions  via path specified by keys

Syntax Definition Result
 (def jsmith {:name “John Smith” :age 50, :address {:postcode “sw 12ap” :Street “Royal Road”}})  defines a map object called jsmith
 (get jsmith :name)  get function returns the key value  “John Smith”
 (get-in jsmith [:address :postcode])  get-in function returns the nested key  “sw 12ap”
(assoc jsmith :age 40) assoc functions associates value to key  (def jsmith {:name “John Smith” :age 40, :address {:postcode “sw 12ap” :Street “Royal Road”}})
(assoc-in jsmith [:address :postcode] “n1 0lk”) assoc-in  associate value to nested key  (def jsmith {:name “John Smith” :age 50, :address {:postcode “n1 0lk” :Street “Royal Road”}})
 (update-in jsmith [:age] inc)  update-in functions is used to apply a function to the key value

inc  function increments  value by 1

 (def jsmith {:name “John Smith” :age 51, :address {:postcode “sw 12ap” :Street “Royal Road”}})

NestedAcessMap

Sets

Set contains unordered list of distinct values

Syntax Definition Result
 #{}  empty set
 #{:a :b}  set with keys a and b
  (#{:a :b} :a)  returns key a from set   :a
 (conj #{:b :c} :a) conj function adds key to set  #{c: :b :a}
(contains? #{:a :e} :e) contains function return a Boolean true
 (contains? #{:a :e} :h)  contains function return a Boolean  false

Set_Data

The screenshot above has been produced using lein repl as for some reasons LightTable from my laptop could not work out # symbol in front of {}.

error#

Starting with Clojure: Factorial function

My background is mainly C# with some JavaScript. I have heard a lot about functional programming languages like Clojure, F# and Scala.

I decided to start learning Clojure.

My first reaction after seeing a Clojure code was the syntax and layout which was unreadable to me.

Clojure is a member of the Lisp family of languages. The use of parentheses is prominent.

Below is some code that calculates factorial of a number in Clojure

(defn fac
"Returns factorial of n"
[n]
(if (= n 1)
1
(* n (fac (- n 1)))))

Parentheses are used to structure lists and lists are building blocks of code.

Each list is just a pair of parentheses with some elements inside and code is data inside list.
The first element of the list is normally the function and the rest of the elements are evaluated and passed to the function as its arguments.
List is a data type but they are also made up of code.

In the code above there is an example of the equals function with n and 1.

(if (= n 1)
1
(* n (fac (- n 1))))

n is the first argument of the call and is used in the condition. If true 1 is returned else the rest of the block is evaluated.

Unlike most languages, Clojure does not have an explicit else statement. It just evaluates the third element to if which is multiplying the number with the factorial of the number minus 1.
Clojure does not have an explicit return, the last expression in a function is used as the return value.

Lisp does not have a concept of operators being different from functions so operators are just functions that compares its arguments.

The environment set up to code in clojure was another challenge

1. IDE
I decided to use Light Table as IDE after reading the stackoverflow post since I was planning to use ClojureScript
http://stackoverflow.com/questions/4248171/choosing-an-ide-editor-for-clojure-coding . It helps greatly with writing Clojure making sure the parentheses are rightly used.

Light Table can be downloaded from http://lighttable.com/

Ctrl/Space open the commands available and type in inst and pick “Instarepl: Open a clojure instarepl” to open REPL.
Instarepl

The factorial function run and evaluated through Light Table IDE.

REPL