
Want this course?
Functional programming
Let's talk about Functional Programming. Then we can talk about combining ingredient lists.
Functional programming
Clojure is a functional programming language. It makes it easy to do functional programming. Functional programming is about approaching the problem by breaking it down into three ideas:
- Data
- Calculation
- Effects
When we change the world, we are doing an effect. So in the bakery, that includes baking stuff, moving around the bakery, or delivery orders. It also includes getting the morning orders, because the orders we get can't be gotten by others.
The orders themselves are data. Data are records. Someone took an order and wrote it down. Now that data can be interpreted.
Calculations are most commonly when you generate new data from existing data. The key feature is that the calculation does not change the world. Calculations are exactly what we need to build one big "shopping list" out of all of the orders. We'll take the order data and calculate the data of the shopping list.
Combining two lists
Let's look at how we can calculate a combined shopping list given two shopping lists. If we have List 1 and List 2, we want to calculate List 3. For each item in List 1, if it exists in List 2, we add the numbers together to get List 3.
There's a function in Clojure called merge-with
that does that. It
takes a function and two hash maps. It will return a new map that has
all of the keys of the two argument maps. And when the same key exists
in both maps, it will apply the function to combine the two values. If
we pass in +
as the function, we get what we just described and we
can take two shopping lists and combine them into one bigger shopping
list.
Exercise 6
Write a function add-ingredients
which takes two ingredient lists
and adds them together using merge-with
.
To navigate to this point in the introduction-to-clojure repo:
$CMD git checkout -f 2.14
Watch me
This function should be easy since it uses an existing function. It
takes two ingredient lists, a
and b
.
(defn add-ingredients [a b]
(merge-with + a b))
To navigate to this point in the introduction-to-clojure repo:
$CMD git checkout -f 2.15
Code is available: lispcast/introduction-to-clojure
Code for this particular lesson is available at the 2.14
branch.
You can checkout the code in your local repo with this command:
$CMD git clone https://github.com/lispcast/introduction-to-clojure.git
$CMD cd introduction-to-clojure
$CMD git checkout -f 2.14