count
, conj
,
first
+
, -
, *
,
/
(defn function-name
[argument-1 argument-2 ...]
body)
(defn function-name
[argument-1 argument-2 ...]
body)
Use defn to create a function.
(defn function-name
[argument-1 argument-2 ...]
body)
Call your function something.
(defn function-name
[argument-1 argument-2 ...]
body)
List the function arguments.
(defn function-name
[argument-1 argument-2 ...]
body)
Write a function body - the code that runs when you call the function.
(defn get-name
; no arguments
[]
; function body, a simple value
"Abraham Lincoln")
(get-name) ;=> "Abraham Lincoln"
Create a function called give-back that takes one argument and returns it.
(give-back 9000) ;=> 9000
(give-back 3.1415) ;=> 3.1415
(give-back "My money!") ;=> "My money!"
(defn total-bill
"Given subtotal of bill, return total after tax."
[subtotal]
(* 1.08 subtotal))
(total-bill 8.5) ;=> 9.18
(total-bill 50) ;=> 54.0
(total-bill 50/6) ;=> 9.0
(defn ; specifies that we are defining a function
total-bill ; the name of this function
;; documentation, optional
"Given subtotal of bill, return total..."
[subtotal] ; list of arguments
;; body of function
(* 1.08 subtotal))
(defn total-with-tip
"Given subtotal, return total after tax and tip."
[subtotal tip-pct] ;; takes 2 arguments
(* 1.08 subtotal (+ 1 tip-pct)))
(total-with-tip 12 0.18) ;=> 15.93
Create a new function, share-per-person
, that takes three
arguments: the subtotal, the tip percent, and the number of people
in the group.
It should call our total-with-tip
function but change
the result to return the average amount each person should pay.
Predicate functions usually end in
?
zero?
vector?
empty?
map
(map plus-one [1 2 3 4 5])
;=> [2 3 4 5 6]
map
map
(def dine-in-orders [12.50 20 21 16 18.40])
(def take-out-orders [6.00 6.00 7.95 6.25])
(map total-bill dine-in-orders)
;=> [13.5 21.6 22.68 17.28 19.872]
(map total-bill take-out-orders)
;=> [6.48 6.48 8.586 6.75]
reduce
(reduce + [1 2 3 4 5]) ;=> 15
(reduce max [8 17 2]) ;=> 17
reduce
reduce
reduce
in action(def take-out-totals [6.48 6.48 8.586 6.75])
(reduce + take-out-totals) ;=> 28.296
reduce
in action(def take-out-totals [6.48 6.48 8.586 6.75])
(reduce + take-out-totals) ;=> 28.296
(+ 6.48 6.48) ;=> 12.96
(+ 12.96 8.586) ;=> 21.546
(+ 21.546 6.75) ;=> 28.296
Create a function called average
that takes a vector of bill amounts and returns the average of those amounts.
Hint: you will need to use the functions reduce
and count
.