How to Map a subset of list elements to a function?
Update: in version 10.2 BlockMap
was added as a System context function.
If the arguments are sequential there is a function Developer`PartitionMap
that does this directly, potentially saving considerable memory over Partition
.
Developer`PartitionMap[f @@ # &, Range@5, 2, 1]
{f[1, 2], f[2, 3], f[3, 4], f[4, 5]}
Syntax is the same as for Partition
but with the function to map inserted as the first argument. Notice in my use above that I needed Apply
(short form @@
) to pass the elements as arguments rather than a single list.
If the arguments are not sequental you can use Part
:
list = {a, b, c, d, e};
parts = {{1, 2}, {4, 1, 3}, {5, 2}};
f @@ list[[#]] & /@ parts
{f[a, b], f[d, a, c], f[e, b]}
You can use
f @@@ Partition[{1,2,3,4}, 2, 1]
which will give
{f[1,2], f[2,3], f[3,4]}
You might first partition your list and then use Map as usual :
f[#[[1]], #[[2]]] & /@ Partition[{1,2,3,4}, 2, 1]
(* {f[1, 2], f[2, 3], f[3, 4]} *)