
Want this course?
orders to ingredients
Now we can write a function that takes a list of orders and gives you the whole list of ingredients you'll need to complete all of them.
Building a total shopping list from a list of orders
When we call get-morning-orders
, we have a list of orders. We will
want to combine them all to get one big shopping list so we can gather
all of the ingredients we need in one go.
There's a function that's made for taking a list of things and
building them up into a single value using a function. It's called reduce
.
Let's assume we want to add some numbers. We can use reduce
to do
that. We pass +
, for adding the numbers. And we start with 0
. reduce
will loop through the list and add each number to the
previous result, until all items are added. Then the value is
returned. We can use reduce
to build up a value using a function, an
initial value, and a list of values.
(reduce + 0 [1 4 5 3 90 23 2 32]) ;=> 157
Exercise 9
Write a function orders->ingredients
that builds a total ingredients
list from a list of orders. You should use for
and reduce
. Instead
of using +
with reduce
, you can use add-ingredients
.
To navigate to this point in the introduction-to-clojure repo:
$CMD git checkout -f 2.17
Watch me
Let's build this up one step at a time. First the signature:
(defn orders->ingredients [orders]
We can use a for
to transform the list of orders into a list of
shopping lists.
(defn orders->ingredients [orders]
(for [order orders]
(order->ingredients order)))
Then we can reduce
all of the shopping lists into a single shopping
list. We will start with an empty map as an empty shopping list and
add each shopping list to it, in sequence.
(defn orders->ingredients [orders]
(reduce add-ingredients {}
(for [order orders]
(order->ingredients order))))
So, there it is.
To navigate to this point in the introduction-to-clojure repo:
$CMD git checkout -f 2.18
Code is available: lispcast/introduction-to-clojure
Code for this particular lesson is available at the 2.17
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.17