Using data structuresλ︎
Data structures in Clojure are used to model information and data, within a particular namespace. Functions are used to run behaviour over the data structures.
Lets look at some of the common functions that are used in Clojure with data structures
fixme the below content is work in progress, sorry.
Managing Return valuesλ︎
If you run a function over a data structure, you may not always get back the type of value you want. It easy to wrap a function around to give you the desired value type.
Note Use the
strfunction to get a string from person, rather than a set of characters
You can get the value of this map
When you use functions on data structures, although they can return a new value they do not change the original data structure.
Lets define a name for a data structure
when we evaluate that name we get the original data we set
Now we use a function called conj to adds (conjoin) another number to our data structure
This returns a new value without changing the original data structure
We cant change the original data structure, it is immutable. Once it is set it cant be changed. However, if we give a name to the result of changing the original data structure, we can refer to that new data structure
Now name2 is the new data structure, but name1 remains unchanged
So we cannot change the data structure, however we can achieve something that looks like we have changed it. We can re-assign the original name to the result of changing the original data structure
Now name1 and name2 are the same result
You have the number 2. If you add 1 to 2, what value is the number 2?
The number 2 is still 2 no mater that you add 1 to it, however, you get the value 3 in return
Creating new data structuresλ︎
Use concat to add lists or vectors together
Use filter, map to interact with collections
Use reduce to reduce them
Reduce can take an initial-value argument too
Use cons to add an item to the beginning of a list or vector
Use conj to add an item to the beginning of a list, or the end of a vector