functional way doing array stuff/ lambda functions
cym13 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Dec 12 15:36:43 PST 2015
On Saturday, 12 December 2015 at 23:10:21 UTC, Namal wrote:
> Hello guys,
>
> I am still uncertain how to do it right when it comes to lambda
> functions.
If you are looking for the functionnal way I'd advise that you
start by
looking up three functions in a language-agnostic way: filter,
map and
reduce. The filter/map/reduce pattern is very common and most
other
functions can be emulated using them. For that reason they exist
in almost
any high-level language. Once you know how to use them well the
rest is
easier.
As a rule of thumb:
- If you have a set of data (for example integers) and want a
smaller set of
data that match some property (for example odd integers) then
the function
to use is "filter". Filter will take a function, use that
function on each
element of the set one at a time, and if it returns false drop
the element
in order to return a new set of data matching the property. For
example:
auto oddData = data.filter!(x => x%2 == 1);
- If you have a set of things (say integers) that you want to
transform into
another thing without changing the number of elements in your
set (say you
want the set of the doubles of each of your integers) then
"map" is the way
to go. Map will take a function, apply it to each element of
the set and
return the set of the results. For example:
auto doubles = data.map!(x => x*2);
- If you have a set of data that you want to combine together
using some rule
(for exemple, to get their product) in order to reduce it to
one thing then
"reduce" is the way to go. It's also called accumulate or fold
in other
languages. Reduce will take a function and a seed and pass the
seed and the
elements of your set in the function, the result becomming the
next seed.
> For instance: how do I multiply all the elements in an array ?
>
> int product(const ref int[] arr){
>
> int p = 1;
> foreach(i;arr)
> p*=i;
> return p;
> }
Here is a good case for reduce. In D it returns a lazy range
(meaning the
result isn't actually computed until you ask for its value), you
can use
.array to force its evaluation.
So, in your example:
int product(const ref int[] arr) {
import std.array: array;
import std.algorithm: reduce;
arr = arr.reduce!((p, i) => p*i).array;
}
More information about the Digitalmars-d-learn
mailing list