Tuesday, 1 December 2015

Confused about the function map & apply?

Hi, everyone.
Today I would like to share some of my thoughts and tips on the two very confusing functions: map and apply.

Well, I find they are very confusing because they can both be applied to a list, they apply the function to elements inside a list,  when the number of elements get more or when the unary function itself get complicated I always feel difficult to picture what the result would be.

In this blog, I want to firstly summarize each function used in Dr. Racket, and secondly show some example results of two functions on a same list, and lastly I'll conclude some of tips and the way I find useful to differentiate and to memorize these two functions.

Firstly,  let's see how Map and Apply work:

map : unary-function list -> list

(map f (list a b c ...)
(list (f a) (f b) (f c) ...) 
map takes a-unary-function and a-list and will produce a list containing the result of using 'a-unary-function' on each element of 'a-list' individually one at a time.  It works like breaking the list at first, applying the unary function on each of the elements and then containing all results into a new-formed list. Remember the result you get will be a list!

apply: unary-function list -> any
(apply f (list a b c ...))
(f a b c...)
The function 'apply' is most useful with functions that take any amount of arguments (or at least lots of arguments). Its main purpose is to work on lists that are computed, rather than known ahead of time.
Basically, what it does is to break the list first and them apply the function on all elements in order. So the result you get could be anything, a number, a boolean, an image, etc.

Suppose we have this list (list 5 6 7 8)
(map - (list 5 6 7 8))
gives us the result 
(list -5 -6 -7 -8)

(apply - (list 5 6 7 8)
gives us the result of -26 calculated as -5-6-7-8=-26

Notice that map can also be used with an unary function and two lists,
(map - (list 5 6 7 8)
           (list 1 2 3 4))
then you will apply the function to numbers at the same positions in each list. 5-1, 6-2...
and get the results of (list 4 4 4 4)

So you see the difference, map will always give us a list!