How to group each element with each consecutive elements in one head
How about a simple table?
Table[f @@ list[[{i, j}]], {i, 4}, {j, i, 4}]
If you want to use this for a general list, you should use Length[list]
in the table iterators or maybe:
With[{n = Length[list]},
Table[f @@ list[[{i, j}]], {i, n}, {j, i, n}]
]
Solutions
Pick[
Outer[f, list, list],
UpperTriangularize@ConstantArray[True, {#, #} &@Length@list]
]
Using the new Composition
shorthand:
Thread@*f @@@ MapIndexed[{#, list[[First@#2 ;;]]} &, list]
Timings
Testing with
list = Range[1000];
the first method takes 0.363 seconds to complete and the second takes 0.120 to complete. As a comparison, halirutan's Table
method took 1.183 to complete. RunnyKine's is the fastest I have tested of the others, taking just 0.336 to complete. All times were measured with AbsoluteTiming
.
This is not the shortest, but faster than all except Pickett's (almost just as fast)
f4 = Thread@f[#[[1]], #] & /@ Partition[#, Length@#, 1, {1, 1}, {}] &
OR
dP = Developer`PartitionMap;
Then:
f5 = dP[Thread@f[#[[1]], #] &, #, Length@#, 1, {1, 1}, {}] &
Timings:
Needs["GeneralUtilities`"]
f1 = With[{n = Length[#]}, Table[f @@ #[[{i, j}]], {i, n}, {j, i, n}]] &;
f2 = MapIndexed[#[[#2[[1]] ;;]] &, Outer[f, #, #]] &;
f3[x_] := Thread@*f @@@ MapIndexed[{#, x[[First@#2 ;;]]} &, x];
BenchmarkPlot[{f1, f2, f3, f4, f5}, RandomInteger[999, #] &, 2^Range[12