Want this course?
We need to go fetch ingredients from different locations. Let's write a function that will go to the right location and fetch an ingredient and bring it back to the prep area.
Fetching ingredients from the pantry
Let's write a function that will bring us to the pantry, get the
ingredient, and bring it back to the prep area. We'll use a similar
pattern to that of the
add-squeezed functions we wrote before. It will be variadic, that is, it will have
two different forms with different numbers of arguments.
First, we define the first form which defaults to one unit.
(defn fetch-from-pantry ([ingredient] (fetch-from-pantry ingredient 1))
It's common to put that easy form first. Now we'll add the second form with two arguments--the ingredient and the amount. We first check if the ingredient is found in the pantry. If it is, we go to the pantry, load up on the ingredients, go back to the prep-area, then unload the ingredients. If it's not from the pantry, we print an error.
(defn fetch-from-pantry ([ingredient] (fetch-from-pantry ingredient 1)) ([ingredient amount] (if (from-pantry? ingredient) (do (go-to :pantry) (dotimes [i amount] (load-up ingredient)) (go-to :prep-area) (dotimes [i amount] (unload ingredient))) (error "This function only works on ingredients that are stored in the pantry. You asked me to fetch" ingredient))))
This demonstrates how we can go fetch ingredients from different parts of the bakery. We first go to the place where they're stored, load up a certain amount, then come back to the prep area and unload that same amount.
Let's write a similar function for fetching from the fridge. It's basically the same, so we'll copy-paste it.
(defn fetch-from-fridge ([ingredient] (fetch-from-fridge ingredient 1)) ([ingredient amount] (if (from-fridge? ingredient) (do (go-to :fridge) (dotimes [i amount] (load-up ingredient)) (go-to :prep-area) (dotimes [i amount] (unload ingredient))) (error "This function only works on ingredients that are stored in the fridge. You asked me to fetch" ingredient))))
Let's copy and paste these into the REPL. We can test. Let's check how much is there in the prep area, then fetch some stuff.
(status) (fetch-from-fridge :milk 20) (status)
(status) (fetch-from-pantry :flour 10) (status)
We can also add fetches to the main function.
(defn -main  (bake-cake) (bake-cookies) (fetch-from-pantry :flour 12) (fetch-from-fridge :egg 45) (status))
Then we run at the terminal:
$CMD lein run
We should expect to see us moving around, and the status should have 12 cups of flour and 45 eggs.
To navigate to this point in the introduction-to-clojure repo:
$CMD git checkout -f 2.7
Code is available: lispcast/introduction-to-clojure
Code for this particular lesson is available at the
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.6