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

ClojureScript – Power of Clojure to the web

ClojureScript is a compiler for Clojure that targets JavaScript. It is designed to emit JavaScript code which is compatible with the advanced compilation mode of the Google Closure optimizing compiler.

Why ClojureScript?

  • Allows to use functional programming.
  • Uses Immutable data structures. (Immutable.js library is available to enable use of immutable data structures with JavaScript. Watch Christian Johansen’s talk on Immutable JavaScript)
  • Uses Google Closure Compiler : advanced code compiling with dead code elimination
  • core.async: makes ajax asynchronous call look like synchronous without the use of callbacks
  • Om/React : React provides a functional approach for rendering DOM. Using ClojureScript and React makes some tasks , for example undo quite simple

A great tutorial to follow to learn ClojureScript is http://clojure.org/clojurescript which covers the basics of ClojureScript, environment set up with the use of Leiningen project, DOM interaction, routing,AJAX call, core.async, Om/React, browser enabled REPL and more.

The difference between JavaScript and ClojureScript is described in Compare ClojureScript with JavaScript.

Below is an example how to create an object in JavaScript and ClojureScript.

Create object in JavaScript
var foo = {foo: "bar"};
Create objects in ClojureScript
;; Create JavaScript objects with `js-obj`.
(def foo (js-obj "foo" "bar"))

;; ClojureScript supports  JavaScript data literals via the `#js` reader literal.
(def foo #js {"foo" "bar"})

;; It’s important to note that `#js` is shallow, the contents of
;;`#js` will be ClojureScript data unless preceded by `#js`.
;; This is a mutable JavaScript object with an immutable
;; ClojureScript object inside.
(def foo #js {"foo" "bar"})

Since I am using LightTable as the IDE,  an introduction to clojureScript to LightTable users is useful. If you are using a Windows machine, use ctrl + enter instead of command +ENTER to evaluate each form.

I got hooked up with the use of React with ClojureScript. The following interfaces are available to integrate React

The advantages and disadvantages of each of the above interface are described in “How to use React in ClojureScript, and why”

Furthermore external JavaScript libraries can be integrated with ClojureScript with the use of :foreign-libs option.

Building Single Page App “SimpleCalculator” with Reagent, Secretary and Accountant 

I followed the figwheel tutorial to create a project based on figwheel leiningen template.

lein new figwheel SimpleCalculator

It automatically creates a directory “SimpleCalculator”.   Open the folder using Light Table. It has the following structure.

figwheelFolderStruc

Open project.clj and add the following dependencies

[reagent "0.5.1"
:exclusions [org.clojure/tools.reader]]
[reagent-forms "0.5.13"]
[reagent-utils "0.1.7"]
[secretary "1.2.3"]
[venantius/accountant "0.1.6"
:exclusions [org.clojure/tools.reader]]

The dependencies tag look like

dependencies

Reagent is the interface for React in ClojureScript. Secretary is client side router for ClojureScript. Accountant makes navigation simple by triggering dispatches to Secretary defined routers and update browser’s path without a page reload.

Open Index.html file. Add the h3 tag above the “app” div.

<h3> Welcome to calculators</h3>

The Index.html will look like

Index

Open core.cljs  and copy and paste the code.

To run the application type
lein figwheel

lein_Figwheel

From the browser navigate to http://localhost:3449

The Maths Calculator is displayed by default

Maths_Calc

Click on BMI link to load the BMI calculator

BMI_Calc

The BMI calculation code has been taken from “Reagent: Minimalistic React for ClojureScript”

Click on Pension Age link to load Pension Age calculator

StateAgeCalc

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

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