|
![]() |
||||||||||||||
List TutorialFunction mapThe list processing that maps a list of elements to another list of elements, by mapping each single element to another, is very often. In previous examples we already presented definition of function incList which computes a list containing elements of list l increased by 1: incList(l) = if l->empty() then [] else (l->hd() + 1):l->tl()->incList(); The only specific part of this function is the application of addition to list elements, while other parts would be absolutely the same for many other list processings. Library function map(l,f) abstracts the computation principle, by parameterisation of the applied function. It is one of the most often used higher order functions. Source code:{# // same as incList([1,2,3]) [1,2,3]->map(operator+(_,1)), [1,2,3]->map(mkList(1,_)) #} where{ mkList(n,m) = if n <= m then n : mkList(n+1,m) else []; // myMap is equvalent to map myMap(l,f) = if l->empty() then [] else l->hd()->f() : l->tl()->map(f); } Result:{# [2,3,4], [[1],[1,2],[1,2,3]] #}
|
|
||||||||||||||
© 2006 Saša Malkov | |||||||||||||||