6
$\begingroup$

I am very surprised not to find this function in the help (or in other questions on this site, which come close)

Is there a Mathematica function f such that

f[{a,b,c,d}] = {{a},{a,b},{a,b,c},{a,b,c,d}}

or must I construct it?

$\endgroup$
2
  • $\begingroup$ Thank you all so much for your quick answers! Going with myfun[x_] := Take[x, #] & /@ Range[Length[x]] $\endgroup$ Commented Jan 15, 2018 at 2:20
  • 2
    $\begingroup$ Recommend myfun[x_?VectorQ] := ... $\endgroup$
    – Bob Hanlon
    Commented Jan 15, 2018 at 2:35

5 Answers 5

8
$\begingroup$
Take[{a, b, c, d}, #] & /@ Range[4]

(* {{a}, {a, b}, {a, b, c}, {a, b, c, d}} *)
$\endgroup$
6
$\begingroup$

Another possibility:

Reverse @ NestList[Most, {a,b,c,d}, 3]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

$\endgroup$
1
  • $\begingroup$ In the same 'vein': FoldList[Flatten[{##}] &, Nothing, {a, b, c, d}] $\endgroup$
    – user1066
    Commented Jan 15, 2018 at 10:28
5
$\begingroup$

Two ideas

f1[l_List] := Rest[FoldList[Append, {}, l]];
f2[l_List] := Table[Take[l, i], {i, Length[l]}]
$\endgroup$
5
$\begingroup$
ReplaceList[{a, b, c, d}, {x__, ___} :> {x}]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

Table[{a, b, c, d}[[;; i]], {i, 4}]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

{a, b, c, d}[[;; #]] & /@ Range@4

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

Partition[{a, b, c, d}, 4, 1, -1, {}]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

Extract[{a, b, c, d}, List /@ Range @ Range @ 4]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

$\endgroup$
2
4
$\begingroup$

For something different

f[x_List] := 
 LowerTriangularize@ConstantArray[x, Length[x]] /. 0 -> Nothing

f[{a, b, c, d}]

{{a}, {a, b}, {a, b, c}, {a, b, c, d}}

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.