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!")

No comments: