Reversing A String
(str (reverse "derp")) ;; => "(\"p\" \"r\" \"e\" \"d\")" (apply str (reverse "derp")) ;; => "pred"
One Plus Two
(+ [1 2]) ;; => [1 2] (+ '(1 2)) ;; => (1 2) (apply + [1 2]) ;; => 3 (apply + '(1 2))
Writings about one coder's stories & experiences.
For someone new To Clojure and ClojureScript it can seem like a bit of a "gotcha" to know when you need to use the apply function and when you don't. Hopefully in this post I'll clear up any confusion about how to apply apply! Let's lay the foundation for this discussion by looking first at some simple examples.
Reversing A String
Suppose we have a string and want to get a string with the characters in reverse order. Here we have two attempts. The first incorrectly creates a stringified list of reversed character strings, but the second creates the desired string.
(str (reverse "derp")) ;; => "(\"p\" \"r\" \"e\" \"d\")" (apply str (reverse "derp")) ;; => "pred"
The key thing to remember is that in Clojure is very focused on dealing with sequences, and when you call reverse on a string it returns a sequence of character string in the reverse order. Str is interesting because it can be called on one thing or more things. If called on just one thing then it stringifies the thing and if passed many arguments it will stringify them and then concatenate them. So, this is why the first incorrect version returns what it does. It sees the list of character strings as one thing- a list, and it then nonchalantly returns the stringified version of the whole list. The second example, on the other hand, is saying take the str function and apply it to all the arguments.
One Plus Two
Now let's look at another example where we want to use the + function on a sequence of numbers. If we pass a vector of quoted list of numbers into + we can see that it returns the same sequence back! This is because the + function is implemented tin a way that it takes multiple parameters and sums them. When we use apply we are telling the compiler to apply the plus function with the contents of the collection as arguments.
(+ [1 2]) ;; => [1 2] (+ '(1 2)) ;; => (1 2) (apply + [1 2]) ;; => 3 (apply + '(1 2)) In General
I think that last example illustrates a nice point that we can formalize more generally, and that is that you use apply when you have a collection and a function that receives some number of arguments and you want to call the function with the collection's contents as the arguments. I don't know about you, but for I look at it like that suddenly it ain't so scary! Have fun applying apply! :)
0 Comments
Your comment will be posted after it is approved.
Leave a Reply. |
AuthorThe posts on this site are written and maintained by Jim Lynch. About Jim...
Categories
All
Archives
August 2021
|