Last active
August 29, 2015 14:08
-
-
Save adam-e-trepanier/4af1bf6782d1083cf356 to your computer and use it in GitHub Desktop.
Working with apply
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns functions.apply) | |
;; We can use apply with print because print takes the (& more) | |
;; parameter. So we can pass any number of args to messenger | |
;; and then apply will explode the sequence generated by (& who) in | |
;; the argument list into the print method | |
(defn messenger "Fooling with apply function" [greeting & who] | |
(println who) | |
(apply print greeting who)) | |
(messenger "Hello" "world" "class" "\n") | |
(messenger "Hello" "Adam" "and" "Ginger" "\n") | |
;; Without the apply function we print the vector world class | |
(print "Hello" ["World" "class"]) | |
;; no more vector | |
(apply print "Hello" ["World" "class"]) | |
(defn add-from-100 | |
"Testing out apply" | |
;; Takes a sequence and then 'explodes' the sequence to the same function | |
;; Trick to using apply is it must send to a function that takes a (rest) | |
;; param. | |
([xs] | |
(apply add-from-100 xs)) | |
;; Here we get the first val and then get the rest of the params. | |
;; Since + takes a rest param (& more) as one of its args we can use | |
;; apply to sum up the rest of our args | |
( [x & xs] | |
(apply + 100 xs))) | |
(add-from-100 1 2 10 100 1000) | |
(add-from-100 [1 3 10 100 1000]) | |
(max 4 2 3 5 7 1 2 99) | |
;; Another example is the max function. Lets say we got a vector of values from | |
;; some data source. If we just use the max function it will output the vector | |
(max [4 2 3 5 7 1 2 99]) | |
;; if we use apply, it will "explode" those values into something max can process | |
;; this works because if you look at (doc max) you will see one of the argument lists | |
;; looks like [x y & more]...essentially x = 4, y = 2, and more is the other data | |
(apply max [4 2 3 5 7 1 2 99]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment