Tuesday, September 08, 2020

#100DaysOfClojure (Day [9] Maps)

Today I will look at Maps, one of the most important collection types in Clojure. Maps are collections of key-value pairs. Keys can be of any type in Clojure including functions, lists, other maps etc. The are 3 types of maps in Clojure: Hash Maps, Sorted Maps and Array Maps. Sorted maps keep the key value pairs in a certain order which implies that a lookup time may not be constant and it also allows you to traverse the values in the order of the keys. Sorted maps have a constraint in that the keys have to be comparable. 


You can create them as follows

; Hash maps
{"number" 1 2 2.25 :pi 22/7}
=> {"number" 1, 2 2.25, :pi 22/7}

or alternatively

(hash-map "number" 1 2 2.25 :pi 22/7)
=> {:pi 22/7, "number" 1, 2 2.25}

;Sorted maps
(sorted-map "number" 1 "2" 2.25 "pi" 22/7)
=> {"2" 2.25, "number" 1, "pi" 22/7}  ; note the order

; you can also sort using a custom comparator
(sorted-map-by #(< (count %1) (count %2))
               "number" 1 "2" 2.25 "pi" 22/7)
=> {"2" 2.25, "pi" 22/7, "number" 1}

You can lookup values as follows

(get {"number" 1 2 2.25 :pi 22/7} :pi)
=> 22/7

or alternatively use the key as a function

(:pi {"number" 1 2 2.25 :pi 22/7})
=> 22/7

if you don't find the key

(get {"number" 1 2 2.25 :pi 22/7} :missing)
=> nil

 You can add new key value pairs as follows

(assoc {"number" 1 2 2.25 :pi 22/7} :association {:a 2.00 :b 5.78})
=> {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}}

You can remove key value pairs as follows

(dissoc {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}} :pi )
=> {"number" 1, 2 2.25, :association {:a 2.0, :b 5.78}}

You can get a list of all the keys as follows

(keys {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> ("number" 2 :pi :association)

You can also get all the values as follows

(vals {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> (1 2.25 22/7 {:a 2.0, :b 5.78})

You can also combine maps as follows

(merge {"2" 2.25, "number" 1, "pi" 22/7} {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> {"2" 2.25, "number" 1, "pi" 22/7, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}}

That's all for today, tomorrow I will move onto Sets

(println "Bye 4 Now!!")

Monday, September 07, 2020

#100DaysOfClojure (Day [8] Vectors)

Vector is another collection data structure that allow random access and add new elements to the end of the collection. 


Here is an example of how you declare a vector:

[1 "Hello" :anytype 22/7]
=> [1 "Hello" :anytype 22/7]

or alternatively

(vector 1 "Hello" :anytype 22/7)
=> [1 "Hello" :anytype 22/7]

You can retrieve any element by using its index which is zero based

(get [1 "Hello" :anytype 22/7] 1)
=> "Hello"

You can get a count of elements as follows

(count [1 "Hello" :anytype 22/7])
=> 4

You can add elements as follows:

(conj [1 "Hello" :anytype 22/7] 2.25)
=> [1 "Hello" :anytype 22/7 2.25]

You can remove an element from the end of the Vector as follows :

(pop [1 "Hello" :anytype 22/7 2.25])
=> [1 "Hello" :anytype 22/7]
 
You can also remove a subset of elements from the vector as follows:

(subvec [1 "Hello" :anytype 22/7 2.25] 1 3)
=> ["Hello" :anytype]
Note the start index is inclusive while the end index is exclusive.

You could also use the nth function as follows:

(nth [1 "Hello" :anytype 22/7 2.25] 2)
=> :anytype

You could also replace values in a Vector using the assoc function

(assoc [1 "Hello" :anytype 22/7 2.25] 1 2 2 3)
=> [1 2 3 22/7 2.25]


That's all on Vectors, tomorrow I will look at Map Collections

(println "Bye 4 Now!")

Sunday, September 06, 2020

#100DaysOfClojure (Day [7] (lists))

The Clojure programming language is designed around data processing which includes the code as data. Today I get into the very foundations of programs in Clojure, the collection data structures. Remember that data in Clojure is immutable so in order for Collections to be efficient they need to be persistent, which means that all the copies have to share the common data. The are 4 collection types, Lists, Vectors, Maps and Sets. And these collections share a set of core functions :

  1. conj - returns a new list with the new add item added
  2. seq - returns sequence to of the collection
  3. count - return the number of items in a collection
  4. empty - returns an empty collection of the same type
  5. = - determine the value equality of one or more collections

I will look specifically at Lists today, and lists in Clojure function similar to linked list in that you have to traverse from start to end (or head to tail). New elements are inserted at the start/front/head of the list. 

You declare a list in the following way

'(1 "hello" :anytype 22/7)
=> (1 "hello" :anytype 22/7)

You may have noticed that the list can contain any types including functions (code)

You can add an element as follows:

(conj '(1 "hello" :anytype 22/7) 2.25)
=> (2.25 1 "hello" :anytype 22/7)

You can count the number of elements in a list

(count '(2.25 1 "hello" :anytype 22/7))
=> 5

You can get the first element as follows:

(first '(2.25 1 "hello" :anytype 22/7))
=> 2.25

You can get the nth value as follows:

(nth '(2.25 1 "hello" :anytype 22/7) 3)
=> :anytype

You can also get the whole list except the first by using the rest function as follows:

(rest '(2.25 1 "hello" :anytype 22/7))
=> (1 "hello" :anytype 22/7)

Equality works as follows:

(= '(1 2 3) '(1 2 3))
=> true
(= '(1 2 3) '(1 2 4))
=> false

There are a few other functions, but will leave that to you to explore. 

Since I have reached a point of having sufficient knowledge of the language to build something real, I will now turn my attention to trying to solve a real life problem as a project. If you have any suggestions for a project please leave a comment...

Tomorrow I will look at Vectors

(println "Bye 4 Now!")

Saturday, September 05, 2020

#100DaysOfClojure (Day [6] Functions Continued)

Today I am continuing with 3 more useful function concepts: How to define functions, anonymous functions and using apply with functions


Functions can be defined in two ways:

(defn name [params] (body))

(def name (fn [params] (body))

 defn is a macro (which I get to some time in the future) doing both a def and fn

The next useful concept is anonymous functions which have a shortened form #() and parameters are specified with a % symbol. Example:

(#(println %) "Hello World!")
Hello World!
=> nil

 You can also use the apply functions on function for each parameter, for example

(apply + '(1 2 3 4))  ; applies the + function on all the values in the list
=> 10

That's all on functions, tomorrow I will look at collections

(println "Bye 4 Now!")

Friday, September 04, 2020

#100DaysOfClojure (Day [5] Functions)

The excitement is building up, today I played with functions. A Clojure function has the following structure

(defn name params (body))

Here is a simple example of a Hello World function definition

(defn sayHello [toName] (println "Hello, " toName))

To call it looks like below with its output

(sayHello "Ahmed")

Hello,  Ahmed
=> nil

There are multi-arity functions which can take a different number of parameters so for example (indents and next line are for readable purposes only):

(defn saySomething 
    ([] (saySomething "Hello world!")) 
    ([msg] (println msg)))

;call the function
(saySomething)
Hello world!
=> nil

(saySomething "Goodbye")
Goodbye
=> nil
 
And there are Variadic Functions which may define a variable number of parameters, for example:

(defn sayManyThings [& thingsToSay] (println thingsToSay))
=> #'leinproj.core/sayManyThings

;call the function
(sayManyThings "Hello" "to" "Ahmed" "and" "friends")
(Hello to Ahmed and friends)
=> nil

There are a few more concepts with functions which I will continue with tomorrow

(println “Bye 4 Now!”) 

Thursday, September 03, 2020

#100DaysOfClojure (Day [4] Basics)

Today I can dip my toes into the language itself. I will be looking at the some of the syntax and forms, Clojure refers to valid code as forms. Clojure has literals which consist of primitive data types, symbols and collections. 


Clojure also has 2 kinds of structures, literals and operations and which follow this format:

(operation argument)

The ( represents a list and an invocation
The operation is a symbol and a function
The argument can be primitive data, a collection or code

Example of adding integers
(+ 1 1)
=> 2

Example of adding ratios
(+ 1/2 1/3)
=> 5/6

Example of subtracting floating point numbers
(- 1.5 0.2)
=> 1.3

Example of adding Hexadecimals
(+ 0x01 0x02)
=> 3

Example of system documentation
(doc +)
-------------------------
clojure.core/+
([] [x] [x y] [x y & more])
  Returns the sum of nums. (+) returns 0. Does not auto-promote
  longs, will throw on overflow. See also: +'
=> nil
*note, even the documentation follows the format, that is how consistent the structure is

There are 4 types of collections : Lists, Vectors, Maps and Sets. All collections are immutable and persistent.

Examples of the collections
 
'(1 2 3)     ; list : they are ordered and can only be accessed by traversing the order
[1 2 3]      ; vector : vectors can be accessed with a index
#{1 2 3}     ; set : the elements are unique and they provide set operations ( union, intersection etc.)
{:a 1, :b 2} ; map : stores key-value pairs


Tomorrow I will look at some function definitions 

(println "Bye 4 Now!")

Wednesday, September 02, 2020

#100DaysOfClojure (Day [3] IntelliJ + Cursive)

With the wide variety of editors/ides available, it was a difficult decision to make. So how did I make this decision you ask? I made the decision based on the quality of the documentation and my familiarity with the editor. Hence I chose IntelliJ and the Cursive plugin. Cursive provide 3 licenses, personal, commercial and non-commercial. Since I am only using it to learn Clojure, I chose the non-commercial licence which is a free 6 month renewable licence.


Getting it up and running was as easy as following the cursive documentation. 
I created a leiningen project which created a folder structure and file with a defined function foo which prints the infamous Hello World message. I loaded the file into the REPL environment and called the function in the REPL input window

(foo "Ahmed Chicktay says ")

Which resulted in 

Ahmed Chicktay says  Hello, World!
=> nil

Here is an image of the entire development environment





















Tomorrow I will look at Clojure literals and if time permits, some of its collections.    

(println “Bye 4 Now”) 

Tuesday, September 01, 2020

#100DaysOfClojure : (+ Day [2] Tools)

Today was a busy and tiring day, so I decided to keep it light and explore the tools available for Clojure. The first tool of importance is Leiningen. It is a build automation and dependency management tool for the Clojure programming language written in Clojure itself. It integrates well with Maven repositories and the Clojars repository for Clojure libraries.  On an Apple Mac you can install Leiningen very easily using homebrew.

















Leiningen provides the following automated tasks to name a few:

  1. The ability to create projects
  2. Compile and package projects
  3. Run projects
  4. Run tests
  5. And more….

There is an alternative build tool called boot, but delving into that is for another day...

Once that was installed I thought I would look for an editor that is Clojure aware and there are a few options in no specific order

  1. Emacs with Cider plugin
  2. Atom with nrepl
  3. Cursive plugin for IntelliJ
  4. Nightcode
  5. Counterclockwise a plugin for Eclipse
  6. Vim with plugins
  7. Light table
  8. SublimeText with SublimeREPL
  9. Netbeans Clojure
  10. VS Code with Calva plugin

I haven’t decided which editor to go with yet, I will leave that for day 3. 

(println “Bye 4 Now”)  

Monday, August 31, 2020

#100DaysOfClojure : (#Day [1] Intro)

I guess you wondering why I chose Clojure as a language to learn as a 100 days of code challenge. Well, functional programming has always intrigued me, but I never could find the time to tinker with it. On discovering that Clojure was designed by Rich Hickey, someone whom I knew understood simplicity, I figured it would be the perfect language to learn from the vast functional ocean. And when you can’t find the time, you have to make the time, so here I am hoping to see out my hundred days. 

My journey started following my usual process: searching duckduckgo for Clojure which led me to this wonderful site: https://clojure.org which has everything one needs to get going. I did some reading on the language to create a mental context and find a starting point to get some running code. 

Clojure is a dynamic general purpose programming language hosted on the Java Virtual Machine (JVM). It is a functional programming language with special features for dealing with concurrency and also a dialect of Lisp. 

My goal for the day is to run the iconic Hello World app of course. I opened a Terminal on a Mac and checked that I have java installed and then used brew to install Clojure. The instructions on the Clojure website are very easy to follow and within minutes I had the REPL up and running











Yippee, that was easy enough for today. I will now spend some time reading The Joy of Clojure…

Saturday, August 03, 2019

throw new InterruptedException()

The InterruptedException is thrown when a Thread is waiting, sleeping or occupied and can be interrupted at any moment in its execution cycle. Since September last year it seems that my writing thread has constantly been interrupted by life, and I feel like I need to do some serious refactoring, maybe build in some new exception handlers and rework the concurrency model. The Writing Thread waited on the inspiration Thread to complete, which as can be seen has been deadlocked and in retrospect was a terrible design choice, so I have decided some time ago to kill the Writing process until the refactoring is done, hopefully I will delete more code from the program then add.....So here is to version 2.0, official release date 12 August 2019 and weekly releases thereafter.

Thursday, September 27, 2018

Thursday, June 08, 2017

Zen and Software Architecture



Zen is a Japanese School of Mahayana Buddhism emphasising the value of meditation and intuition. Zen is not a theory, an idea or piece of knowledge, it is not a belief, a dogma, or a religion, it is a practical experience. It rejects metaphysical theories and rituals and focuses on letting go of your ego and merging with the universe. What has this all got to do with software architecture you are wondering? 

Well, I am going to answer that with a Zen koan, which refers to a story or parable which zen novices meditate on. The effort to understand or solve a koan is intended to exhaust the intellect and open the intuition so that we can understand and experience more of ourselves. 

So I leave you with this koan and look forward to hearing about your experiences with it.


The Taste of Banzo’s Sword

Matajuro Yagyu was the son of a famous swordsman. His father, believing that his son's work was too mediocre to anticipate mastership, disowned him.
So Matajuro went to Mount Futara and there found the famous swordsman Banzo. But Banzo confirmed the father's judgment. "You wish to learn swordsmanship under my guidance?" asked Banzo. "You cannot fulfill the requirements."
"But if I work hard, how many years will it take me to become a master?" persisted the youth.
"The rest of your life," replied Banzo.
"I cannot wait that long," explained Matajuro. "I am willing to pass through any hardship if only you will teach me. If I become your devoted servant, how long might it be?"
"Oh, maybe ten years," Banzo relented.
"My father is getting old, and soon I must take care of him," continued Matajuro. "If I work far more intensively, how long would it take me?"
"Oh, maybe thirty years," said Banzo.
"Why is that?" asked Matajuro. "First you say ten and now thirty years. I will undergo any hardship to master this art in the shortest time!"
"Well," said Banzo, "in that case you will have to remain with me for seventy years. A man in such a hurry as you are to get results seldom learns quickly."
"Very well," declared the youth, understanding at last that he was being rebuked for impatience, "I agree."
Matajuro was told never to speak of fencing and never to touch a sword. He cooked for his master, washed the dishes, made his bed, cleaned the yard, cared for the garden, all without a word of swordsmanship.
Three years passed. Still Matajuro labored on. Thinking of his future, he was sad. He had not even begun to learn the art to which he had devoted his life.
But one day Banzo crept up behind him and gave him a terrific blow with a wooden sword.
The following day, when Matajuro was cooking rice, Banzo again sprang upon him unexpectedly.
After that, day and night, Matajuro had to defend himself from unexpected thrusts. Not a moment passed in any day that he did not have to think of the taste of Banzo's sword.
He learned so rapidly he brought smiles to the face of his master. Matajuro became the greatest swordsman in the land.