maps,filter,folds and more? Do we really need these in Erlang? -
maps, filters, folds , more : http://learnyousomeerlang.com/higher-order-functions#maps-filters-folds
the more read ,the more confused.
can body simplify these concepts?
i not able understand significance of these concepts.in use cases these needed?
i think majorly because of syntax,diff find flow.
the concepts of mapping, filtering , folding prevalent in functional programming simplifications - or stereotypes - of different operations perform on collections of data. in imperative languages these operations loops.
let's take map
example. these 3 loops take sequence of elements , return sequence of squares of elements:
// c - lot of bookkeeping int data[] = {1,2,3,4,5}; int squares_1_to_5[sizeof(data) / sizeof(data[0])]; (int = 0; < sizeof(data) / sizeof(data[0]); ++i) squares_1_to_5[i] = data[i] * data[i]; // c++11 - less bookkeeping, still not obvious std::vec<int> data{1,2,3,4,5}; std::vec<int> squares_1_to_5; (auto = begin(data); < end(data); i++) squares_1_to_5.push_back((*i) * (*i)); // python - quite readable, though still not obvious data = [1,2,3,4,5] squares_1_to_5 = [] x in data: squares_1_to_5.append(x * x)
the property of map
takes collection of elements , returns same number of somehow modified elements. no more, no less. obvious @ first sight in above snippets? no, @ least not until read loop bodies. if there if
s inside loops? let's take last example , modify bit:
data = [1,2,3,4,5] squares_1_to_5 = [] x in data: if x % 2 == 0: squares_1_to_5.append(x * x)
this no longer map
, though it's not obvious before reading body of loop. it's not visible resulting collection might have less elements (maybe none?) input collection.
we filter
ed input collection, performing action on elements input. loop map
combined filter
.
tackling in c more noisy due allocation details (how space allocate output array?) - core idea of operation on data drowned in bookkeeping.
a fold
generic one, result doesn't have contain of input elements, somehow depends on (possibly of) them.
let's rewrite first python loop in erlang:
lists:map(fun (e) -> e * e end, [1,2,3,4,5]).
it's explicit. see map, know call return list long input. , second one:
lists:map(fun (e) -> e * e end, lists:filter(fun (e) when e rem 2 == 0 -> true; (_) -> false end, [1,2,3,4,5])).
again, filter
return list @ long input, map
modify each element in way.
the latter of erlang examples shows useful property - ability compose map
s, filter
s , fold
s express more complicated data transformations. it's not possible imperative loops.
Comments
Post a Comment