This is a very simple example that illustrates the the ‘map’ concept used in functional programming. This example is written in F#.
Mapping is a popular programming concept that lets you apply a function to each element of a list or collection. The return value of a map operation is another list. Because the same function is applied to each element of the list, there is no reason why the process cannot be done concurrently, thus lending itself to distributing computing algorithms (I’ll have another post soon about MapReduce using Hadoop).
let numbers = [1;2;3;4;5] let squares = List.map (fun x -> x*x) numbers printf "Numbers squared = %A" squares
This example simply squares the numbers in a list. The output is another list, with each item in the original list squared.
You can also use map to process more than one list at a time.
let numbers = [1;2;3;4;5] let letters = ["a";"b";"c";"d";"e"] let tuples = List.map2 (fun x y -> (x, y)) numbers letters printf "%A" tuples
If mapping over two list isn’t enough, there is also a List.mapi function that will map over an arbitrarily long list of lists. Functional programming is really entertaining if you’re used to traditional procedural languages like C and Java. Hopefully this gives you a taste of the fun things you can do!
