| Bytes | Lang | Time | Link |
|---|---|---|---|
| 060 | Nim | 250801T173409Z | janAkali |
| 075 | AWK | 250731T182503Z | xrs |
| 008 | TinyAPL beta 0.13 | 250603T144823Z | RubenVer |
| 037 | Swift 6 | 250515T130153Z | macOSist |
| nan | 181207T191817Z | flawr | |
| 024 | Juby | 250514T192000Z | Jordan |
| 054 | Swift | 230119T171731Z | SimonL |
| 072 | Go | 230119T180315Z | bigyihsu |
| nan | 230119T174651Z | The Thon | |
| 4911 | D | 181210T144334Z | FeepingC |
| 011 | x86 opcode | 230119T112549Z | l4m2 |
| 029 | Arturo | 230119T101407Z | chunes |
| 012 | MATL | 181209T222225Z | Suever |
| 006 | Pip | 220308T163757Z | DLosc |
| 026 | Julia 1.0 | 220308T162334Z | MarcMush |
| 008 | Brachylog | 181211T083556Z | Fatalize |
| 006 | Pyth | 220308T143902Z | sinvec |
| 003 | Vyxal | 210531T023921Z | wasif |
| 025 | Factor + grouping.extras | 210531T025157Z | chunes |
| 014 | Add++ | 210506T154253Z | caird co |
| 102 | Google Sheets | 201203T184630Z | General |
| 028 | Scala | 201202T192443Z | user |
| 007 | K ngn/k | 181207T202529Z | ngn |
| 060 | Reticular | 190111T013124Z | Wisław |
| 097 | C gcc | 181209T120256Z | user7740 |
| 021 | Scala | 181210T080319Z | Brian Mc |
| 008 | 05AB1E | 181223T001833Z | krinisto |
| 034 | Bash | 181213T214335Z | philcolb |
| 012 | APL Dyalog Unicode | 181213T165412Z | J. Sall& |
| 037 | Elixir | 181213T140822Z | Kirill L |
| 072 | Gambit Scheme gsi | 181212T185041Z | sporkl |
| 013 | Actually | 181212T194650Z | user4594 |
| 024 | Perl 5 + a | 181211T201506Z | Dom Hast |
| 013 | Perl 6 | 181207T225310Z | Sean |
| 029 | Ruby | 181209T114716Z | Asone Tu |
| 031 | Ruby | 181208T212631Z | Eric Dum |
| 021 | Clojure | 181211T000250Z | NikoNyrh |
| 006 | str | 181210T233523Z | Conor O& |
| 022 | SWI PROLOG | 181210T224517Z | styrofoa |
| 077 | Java 8+ | 181208T002248Z | ბიმო |
| 006 | MathGolf | 181210T125923Z | Kevin Cr |
| 007 | MathGolf | 181210T144613Z | maxb |
| 039 | R | 181207T201218Z | Giuseppe |
| 057 | FALSE | 181210T023520Z | Terjerbe |
| 012 | brainfuck | 181208T085629Z | Jo King |
| 045 | F# Mono | 181209T110233Z | dana |
| 057 | Forth gforth | 181209T091715Z | Maya |
| 018 | Z80Golf | 181209T090917Z | Maya |
| 063 | Factor | 181209T061118Z | cat |
| 039 | C# Visual C# Interactive Compiler | 181209T043257Z | dana |
| 007 | MY | 181207T232705Z | Adalynn |
| 065 | Tcl | 181208T115947Z | sergiol |
| 007 | Pushy | 181208T093348Z | FlipTack |
| 004 | Japt | 181207T200518Z | Kamil Dr |
| 024 | Powershell | 181208T082724Z | mazzy |
| 033 | JavaScript ES6 | 181207T192258Z | Arnauld |
| 032 | Kotlin | 181208T081338Z | snail_ |
| 076 | Red | 181208T080835Z | Galen Iv |
| 043 | brainfuck | 181208T070800Z | user2027 |
| 016 | Pip | 181208T050115Z | ASCII-on |
| 023 | Pari/GP | 181208T045413Z | alephalp |
| 081 | Tcl | 181208T000529Z | ASCII-on |
| 092 | Lua 5.3 | 181208T022738Z | cyclamin |
| 005 | Japt | 181208T021135Z | Oliver |
| 013 | Attache | 181208T005214Z | Conor O& |
| 002 | Husk | 181208T003549Z | ბიმო |
| 053 | F# | 181207T234730Z | Ciaran_M |
| 048 | C# Visual C# Interactive Compiler | 181207T235135Z | ASCII-on |
| 037 | Groovy | 181207T232500Z | GolfIsAG |
| 039 | Common Lisp | 181207T231822Z | ASCII-on |
| 021 | Mathematica | 181207T213352Z | LegionMa |
| 036 | JavaScript | 181207T211619Z | Oliver |
| 007 | RAD | 181207T205514Z | Adalynn |
| 003 | 05AB1E | 181207T204327Z | Okx |
| 032 | Python 2 | 181207T201533Z | ovs |
| 005 | Canvas | 181207T194519Z | dzaima |
| 065 | PowerShell | 181207T193803Z | AdmBorkB |
| 020 | Haskell | 181207T194346Z | Ørj |
| 003 | Jelly | 181207T200323Z | Dennis |
| 006 | Charcoal | 181207T200219Z | Neil |
| 027 | Haskell | 181207T193414Z | flawr |
| 005 | J | 181207T192614Z | FrownyFr |
AWK, 75 bytes
{for(s="[[]";i++<NF;){s=s", [";for(j=0;j++<i;)s=s $j (j-i?",":"]")}}$0=s"]"
TinyAPL (beta 0.13), 8 bytes
⦅⍬⊂⊸⍪⊂\⦆
⦅⍬⊂⊸⍪⊂\⦆
⊂⊸⍪ ⍝ Prepend
⍬ ⍝ the empty list
⊂\ ⍝ to the list of nonempty prefixes
💎
Created with the help of Luminespire.
CW for all trivial entries
Clean, 19 bytes
Haskell version works in Clean too.
import StdLib
inits
Haskell, 22 bytes
import Data.List
inits
Prolog (SWI), 6 bytes
prefix
Vyxal 3, 1 byte
P
Swift, 60 54 bytes
let f={(i:[Int])in return[[]]+i.indices.map{i[...$0]}}
Defines a function that takes an array of ints and returns an Array of ArraySlices (i.e, they reference the same memory as the input array). To turn into real arrays, it's 67 61 bytes.
let f={(i:[Int])in return[[]]+i.indices.map{Array(i[...$0])}}
Go, 72 bytes
func(I[]int)(o[][]int){for i:=0;i<=len(I);i++{o=append(o,I[:i])};return}
Generic, 77 bytes
func f[T any](I[]T)(o[][]T){for i:=0;i<=len(I);i++{o=append(o,I[:i])};return}
Thunno, \$ 11 \log_{256}(96) \approx \$ 9.05 bytes
0TzreRz0sAI
Explanation
0TzreRz0sAI # Implicit input
0T # Append a 0 (so the length is increased by 1)
zr # Length range, [0..len)
e # Map over this list:
R # Range from 0 to this number
sAI # Index this into
z0 # The input
# Implicit output
D, 49 bytes (11 imports, 38 expression)
import std;
alias prefixes = t=>iota(t.length+1).map!(i=>t.take(i));
edit: Do I count the alias prefixes = part? You can use the lambda without it, but you have to add parens to disambiguate, so should I count it as 42?
edit: We now got import std; as a shortcut. That solves things!
x86 opcode, 11 bytes
xor eax, eax
inc ecx
P:
xchg eax, esi
stosd
xchg eax, esi
stosd
inc eax
loop P
ret
Take ecx(length) esi(input array) edi(output buffer) output (array,length) pairs
Somehow cheaty :)
MATL, 15 12 bytes
3 bytes saved thanks to @Giuseppe
vin:"G@:)]Xh
Try it at MATL Online.
Due to the way that MATL displays the output, you can't explicitly see the empty array in the cell array. Here is a version that shows the output a little more explicitly.
Explanation
v # Vertically concatenate the (empty) stack to create the array []
i # Explicitly grab the input
n # Compute the number of elements in the input (N)
: # Create an array from [1, ..., N]
" # Loop through this array
G # For each of these numbers, M
@: # Create an array from [1, ..., M]
) # Use this to index into the initial array
] # End of the for loop
Xh # Concatenate the entire stack into a cell array
Pip, 6 bytes
_H,U#_
Anonymous function that takes an iterable and returns a list of iterables. (A full program would be the same number of bytes, but would require flags.) Attempt This Online!
Explanation
#_ ; Length of function argument
U ; Incremented
, ; Range from 0 up to one less than that number, i.e. 0..len
_H ; For each of those numbers n, get the first n elements of the function argument
Julia 1.0, 26 bytes
~l=0:length(l).|>i->l[1:i]
alternative solution in Julia 1.6+, 26 bytes:
~l=first.([l],0:length(l))
Try it online!
Brachylog, 9 8 bytes
{∧Ė|a₀}ᶠ
Explanation
{ }ᶠ Find all:
∧Ė The empty list
| Or
a₀ A prefix of the input
Factor + grouping.extras, 25 bytes
[ head-clump { } prefix ]
Mostly a built-in. Just have to add the empty list at the beginning.
Compare to a non-trivial answer:
[ dup length [0,b] [ head ] with map ]
Add++, 14 bytes
L*,¬b[€bFbUBpA
How it works
L ; Lambda function. Takes A as argument
*, ; Return the enire stack
; E.g. A = [1 2 3 4]
¬b[ ; Scan pair; STACK = [[1 [1 2] [[1 2] 3] [[[1 2] 3] 4]]]
€bF ; Flatten each; STACK = [[[1] [1 2] [1 2 3] [1 2 3 4]]]
bU ; Splat; STACK = [[1] [1 2] [1 2 3] [1 2 3 4]]
Bp ; Pop each; STACK = [[] [1] [1 2] [1 2 3]]
A ; Push A; STACK = [[] [1] [1 2] [1 2 3] [1 2 3 4]]
Google Sheets, 102
- Input is in Row 1
- A2:
COUNTA(1:1) - Output:
=ArrayFormula(IF(A2,{T(SEQUENCE(1,A2));IF(SEQUENCE(A2)>=SEQUENCE(1,A2),OFFSET(A1,,,,A2),)},
Output Formatted:
=ArrayFormula(IF(
A2,
{
T(SEQUENCE(1,A2));
IF(
SEQUENCE(A2)>=SEQUENCE(1,A2),
OFFSET(A1,,,,A2),
)
},
))
Scala, 28 bytes
_.scanLeft(Seq[Int]())(_:+_)
This is longer than the Scala answer that's already here, but uses a different method. Unfortunately, the [Int] must be used to avoid Nothing being inferred.
Reticular, 60 bytes
Bql:D=:D`:E=l[:D`@d]~*[:E`b@qM[$]:D`:E`-*:E`1-:E=]:D`1+*lbo;
Assumes that the input list is at the top of the stack. To test input, run the following code
'1''2''3''4''5'lbBql:D=:D`:E=l[:D`@d]~*[:E`b@qM[$]:D`:E`-*:E`1-:E=]:D`1+*lbo;
Explanation
B # Push every element from the input list to the stack.
q # Reverse stack.
l # Push the size of the stack to the stack.
:D= # Save it as the variable D.
:D`:E= # Define the variable E = D.
l # Push D to the stack.
[:D`@d] # Push the function which duplicates the top D items in the stack
~ # Swap the top two items in the stack
* # Call the above function D number of times.
[ ] # Push a function that does the following:
:E`b # Put the top E items in a list.
@q # Reverse list that is at the top of the stack.
M # Rotate stack so that top of stack -> bottom of stack.
[$]:D`:E`-* # Delete the top D-E items from the stack.
:E`1-:E= # Define E = E - 1.
:D`1+* # Call the above function D+1 number of times.
q # Reverse stack.
lb # Put every item in the stack into a list.
o; # Output the resulting list and exit.
C (gcc), 102 97 bytes
Pretty long, as C quite obviously isn't well-suited to manipulating lists of lists. Dependent on certain behavior; running on some platforms requires changing int to short (for +2 bytes), due to wchar_t being UTF-16 rather than UTF-32. Should work on Linux as-is.
Takes in a pointer to the first element of the input array, the length of the array, and a pointer to the variable in which the pointer to output will be stored. Produces a list of lists such that the first integer in the linear array stores the number of sub-lists. Sub-lists start with the number of elements, and are stored in memory in a contiguous manner.
p(r,e,f,i,x)int*e,**r,*x;{x=*r=malloc(4-++f*~f*2);*x++=f;for(i=0;i<f;x+=++i)wmemcpy(x+1,e,*x=i);}
Degolf
p(r,e,f,i,x) int**r,*e,*x; // Function p(), where r is a pointer to the output variable,
// e is a pointer to the input location and f is the size of
// the input.
{
x=*r=malloc(4-++f*~f*2); // Allocate 4*(x+1)*(x+2)/2+4 bytes of memory.
// This is the exact amount of memory needed.
*x++=f; // Store n+1 (number of sub-lists) in the first four bytes.
for(i=0;i<f;x+=++i) // Iterate over [0, n]->i and
// increment the pointer to x by i+1 every iteration.
wmemcpy(x+1,e,*x=i); // Set first element at location pointed to by x to i,
// then copy i of either 2 or 4 byte elements, depending on
// the system wchar implementation, to location pointed to
// by x+1.
}
Scala, 21 bytes
_.inits.toSeq.reverse
Not quite a trivial answer, since I had to deal with the fact that the inits method returns an iterator in the reverse of the required order.
05AB1E, 8 bytes
That was my first succesfull golf! Thanks for being such a nice community!
)UŒ¹g£Xš
Explanation:
)UŒ¹g£Xš
) : Create an empty list
U : Save it to variable ˙X˙
Œ : Make the "substrings" of the implicit input
¹g£ : Take the first n elements of the result where n is the lenght of input
Xš : Add the empty list to the beginning
Bash, 34 bytes
I output each list element on a new line as someone else did - bash only has 1-D arrays:
for((;c<=$#;c++)){ echo ${*:1:c};}
Could be 1 byte less but this does not work for null case - don't see why... c++ does not get evaluated...
for((;c<=$#;)){ echo ${*:1:c++};}
This can output text as suggested by OP:
C='echo -n ';A=(${1//[],[]/ });$C[[];for((c=0;c<${#A[*]};)){ B=${A[*]::++c};$C,[${B// /,}];};echo ]
No one should have to decode that. Here is annotated version:
C='echo -n ' # basically a macro to improve my golf
A=( ${1//[],[]/ } ) # convert [,] to spaces - like magic this one
$C[[] # echo [[] since every list needs this
for((c=0;c<${#A[*]};)){ # for all elements of list
B=${A[*]::++c} # make space separated list of first c elements
$C,[${B// /,}] # prefix with ,[ and convert space to comma
}
echo ] # terminate list with ]
APL (Dyalog Unicode), 12 bytes
(0,∘⍳∘≢⊢)↑¨⊂
Prefix tacit function. TIO link has boxing enabled to make the output more readable.
How:
(0,∘⍳∘≢⊢)↑¨⊂ ⍝ Tacit fn, taking a vector as argument, which will be called ⍵ for simplicity.
↑ ⍝ Take the first ⍺ (left arg) elements of ⍵
¨⊂ ⍝ Since the ⍺ for ↑ is a vector, we enclose the ⍵ and apply ↑ to it for each of the elements in ⍺.
( ⊢) ⍝ Use ⍵ as argument for
≢ ⍝ Tally; yields the number of elements in ⍵
⍳∘ ⍝ Then, yield the range [1..≢⍵]
0,∘ ⍝ and prepend a 0.
The function returns a vector of vectors, each with the first [0..≢⍵] elements of the argument.
Elixir, 37 bytes
fn x->Enum.scan [[]|x],&(&2++[&1])end
Looking at other languages, this looks rather verbose, but I'm definitely not an expert in Elixir, so please let me know if I missed something obvious.
Gambit Scheme (gsi), 77 72 bytes
(define(p z)(if(pair?(car z))(p(cons(reverse(cdr(reverse(car z))))z))z))
First time using Scheme. It's a function that takes a wrapped list ((list (list 1 2 3 4))) as an argument.
Actually, 13 bytes
;╗ru⌠╜H⌡M[]@o
Explanation:
;╗ru⌠╜H⌡M[]@o
;╗ save a copy of input in register 0
ru range(1, len(input)+1)
⌠╜H⌡M for i in range:
╜H first i elements of input
[]@o prepend an empty list
Perl 6, 13 bytes
{(),|[\,] @_}
To explain:
In Perl 6 you can wrap an operator in square brackets as an alternate way to write a list reduction. [+] @array returns the sum of the elements in @array, [*] @array returns the product, etc. You can also precede the operator with a backslash to make a "triangular" reduction, which some languages call "scan." So [\+] @array returns a list consisting of the first element of @array, then the sum of the first two elements, then the sum of the first three elements, etc.
Here [\,] @_ is a triangular reduction over the input array @_ using the list construction operator ,. So it evaluates to a lists of lists: the first element of @_, the first two elements of @_, etc. That's almost what's needed, but the problem calls for a single empty list first. So the first element of the return list is a literal empty list (),, then the reduction over the input list is flattened into the rest of the return list with |.
Ruby, 31 29 bytes
->a{[a*i=0]+a.map{a[0,i+=1]}}
Explanation:
->a{ # take array input a
[a*i=0]+ # set i to 0 and add whatever comes next to [[]] (a*0 == [])
a.map{ # for every element in a (basically do a.length times)
a[0,i+=1] # increment i and return the first i-1 elements of a to map
}
}
Clojure, 21 bytes
#(reductions conj[]%)
str, 6 bytes
e;:dno
Each output line corresponds to an entry in the prefix array.
Explanation
e;:dno
-- preamble --
e push empty string
-- iteration --
: append current char to build string
d duplicate it
n push "\n"
o output it
(implicitly output duplicated entry)
SWI PROLOG 22 bytes
i(X,Y):-append(X,_,Y).
Java 8+, 86 77 bytes
-9 bytes thanks to Kevin Cruijssen (getting rid of the import)!
x->java.util.stream.IntStream.range(0,x.size()+1).mapToObj(t->x.subList(0,t))
Alternative, 65 bytes
The following will print the results to stdout (due to Olivier Grégoire):
x->{for(int i=0;i<=x.size();)System.out.print(x.subList(0,i++));}
MathGolf, 9 7 6 bytes
hÅ_╡]x
-1 byte thanks to @maxb.
Try it online or verify all test cases.
Explanation:
h # Push the length of the (implicit) input-array, without popping the array
Å # Loop this length amount of times,
# and do the following two commands each iteration:
_ # Duplicate the array at the top of the stack
╡ # Remove the right-most item of the array
] # After the loop, wrap everything on the stack in an array
x # Reverse it (and output implicitly)
MathGolf, 7 bytes
hæ_ï<\]
Explanation
h length of array/string without popping
æ start block of length 4
_ duplicate TOS
ï index of current loop, or length of last loop
< slice list
\ swap top elements
] end array / wrap stack in array
R, 40 39 bytes
function(L)lapply(0:length(L),head,x=L)
-1 byte thanks to digEmAll
The output of R's list type is a bit weird; it uses sequential indexing, so for instance, the output for
list(1,2) is
[[1]] # first list element
list()
[[2]] # second list element
[[2]][[1]] # first element of second list element
[1] 1
[[3]] # third list element
[[3]][[1]] # first element of third list element
[1] 1
[[3]][[2]] # etc.
[1] 2
Taking input as a vector instead gives a neater output format, although then the inputs are not technically lists.
FALSE, 57 bytes
1^[$~][\1+^]#%a:0[$a;1->~][0[$@$@>][\$a;\-ø,1+]#\%10,1+]#
Try it online! (you'll have to copy paste the code. Click "Show" and then run)
Like brainf*ck, FALSE only takes one char at a time as input, so this program splits a string into prefixes, separating them with a newline.
Explanation:
1^ {push 1 {counter) and first character onto stack}
[$~][ {while a character is input:}
\1+^ {add 1 to the counter}
]#
% {drop truth value from stack}
a: {define the counter as the variable "a'}
0 {push 0 onto stack (loopvar)}
[$a;1->~][ {while loopvar is less than a-1:}
0 {push 0 (loopvar2)}
[$@$@>][ {while loopvar is greater than loopvar2}
\$a;\- {a-loopvar2 (to get index of char to print)}
ø, {copy value at index to top of stack and print}
1+ {increment loopvar2}
]#
\% {swap'n'drop (get rid of loopvar2)}
10, {print newline}
1+ {increment loopvar}
]#
A FALSE expert could probably do this using no variables (pure stack) but since I only learnt this language yesterday I think this is alright.
brainfuck, 21 12 bytes
-9 bytes thanks to Arnauld suggesting the separator ÿ instead of newlines
-[[<]>[.>],]
Takes bytes through STDIN with no null bytes and prints a series of prefixes separated by the ÿ character with a leading ÿ character. For example, for the input Prefixes, the output is ÿÿPÿPrÿPreÿPrefÿPrefiÿPrefixÿPrefixeÿPrefixes.
For readability, here's a version with newlines instead.
Explanation:
- Create a ÿ character in cell 0
[ ,] While input, starting with the ÿ
[<]> Go to the start of the string
[.>] Print the string
, Append the input to the end of the string
F# (Mono), 45 bytes
fun x->List.mapi(fun i y->List.take i x)x@[x]
I am not totally sure if this is valid, but it seems like it follows the same "anonymous lambda" syntax that I've seem used in several other languages.
Forth (gforth), 57 bytes
: x here 0 begin 2dup type cr 1+ key dup c, 5 < until ; x
Takes bytes through STDIN and prints a series of prefixes, each terminated by a newline.
Z80Golf, 18 bytes
00000000: 2511 00ff 1b1a ffa7 20fa cd03 802b 7730 %....... ....+w0
00000010: f076 .v
Takes bytes through STDIN with no null bytes and prints a series of prefixes, each terminated by a null byte.
Source code:
dec h
start:
ld de, $ff00
.printloop:
dec de
ld a, (de)
rst $38
and a
jr nz, .printloop
call $8003
dec hl
ld (hl), a
jr nc, start
halt
Factor, 63 bytes
USE: fry [ [ dup '[ nip _ swap head ] map-index ] keep suffix ]
Keeps a copy of the input to tack on at the end, like C#.
C# (Visual C# Interactive Compiler), 39 bytes
x=>x.Select((_,i)=>x.Take(i)).Append(x)
MY, 7 bytes
ωωι0;↑←
Woah ... never thought MY would actually come in handy.
How?
ωωι0;↑←
ω=push(arg[0])ω=push(arg[0])ι=push([1 ... pop()])0=push(0);=push(pop() + pop())↑= does the prefixing work by vecifying in a stupid manner.←output
Japt, 4 bytes
²£¯Y
Explanation:
² :Add an arbitrary extra item to the end of the array
£ :For each item in the new array:
¯Y : Get an array of the items that are before it
Powershell, 24 bytes
,@()
$args|%{,($x+=,$_)}
Explanation:
- The trivial accumulator wrapped to array by unary
,. - The script uses splatting. See parameter
@a.
Test script:
$f = {
,@()
$args|%{,($x+=,$_)}
}
@(
,( @() , @() )
,( @(42) , @(@(),@(42)) )
,( @(1,2,3,4) , @(@(), @(1), @(1,2), @(1,2,3), @(1,2,3,4)) )
,( @(4,3,2,1) , @(@(), @(4), @(4,3), @(4,3,2), @(4,3,2,1)) )
) | % {
$a,$expected = $_
$result = &$f @a
$false -notin $(
$result -is [array]
$result.Count -eq $expected.Count
for($j=0; $j-lt$result.Count; $j++){
"$($result[$j])" -eq "$($expected[$j])"
}
)
# $result # uncomment this line to display a result
}
Output:
True
True
True
True
JavaScript (ES6), 33 bytes
a=>[b=[],...a.map(n=>b=[...b,n])]
How?
+--- a = input array
|
| +--- initialize b to an empty array and include it as the first entry
| | of the output (whatever the input is)
| |
| | +--- for each value n in a[]:
| | |
| | | +--- append n to b[] and include this new array in
| | | | the final output
| | | |
a => [b = [], ...a.map(n => b = [...b, n])]
| |
+---------+--------+
|
spread syntax: expands all elements of
the child array within the parent array
Kotlin, 32 bytes
{l->(0..l.size).map{l.take(it)}}
{ list ->
(0..list.size).map { // map over range [0, length of list]
list.take(it) // first n items of list
}
}
Red, 76 bytes
func[b][a: copy[[]]c: b until[append/only a copy/part b c: next c tail? c]a]
brainfuck, 43 bytes
Take a list of non-null characters as input and returns all prefixes separated by newline. Requires double-infinite or wrapping tape.
,>-[+>,]<[-<]<<++++++++++[[<]>[.>]>[-<+>]<]
Pip, 16 bytes
{h@<a}M,1+#(h:a)
Explanation
M Map
{h@<a} Function returning global variable h, cut at index a, and left part taken (0-indexed)
, Range from 1 to
1+#( ) 1 + the length of
h:a Assign global variable h to a, evaulating to the value of h (which is also the value of a - the first parameter to the function)
Tcl, 81 bytes
set i -1
set a {{}}
foreach _ $argv {lappend a [lrange $argv 0 [incr i]]}
puts $a
Lua 5.3, 92 bytes
function f(...)t=...if#t>0then return f({table.unpack(t,1,#t-1)},...)else return{...}end end
Keeps creating a copy of the array-like table with the element at the end removed and prepending it to the varargs until the length of the table is 0, then puts the varargs in a table. Relies on defining the variable f to allow recursion.
Lua 5.1, 87 bytes
function f(...)t=...if#t>0 then return f({unpack(t,1,#t-1)},...)else return{...}end end
unpack is a global variable rather than a member of the table library. 0then is syntactically invalid in Lua 5.1, but strangely not in Lua 5.3.
Attache, 13 bytes
{_[0...0:#_]}
Explanation
{_[0...0:#_]}
{ } block taking `_` as input
_[ ] index from the input
0:#_ range from 0 to the length of `_` inclusive
0... range from 0 to each number that range, right exclusive
Husk, 2 bytes
Θḣ
Gets all the ḣeads and then prepends Θ (in this case []):
(needs type annotation for empty list: Try it online!)
F#, 53 bytes
I've actually got two pretty similar answers for this, both the same length. They both take a generic sequence s as a parameter.
First solution:
let i s=Seq.init(Seq.length s+1)(fun n->Seq.take n s)
Seq.take takes the first n elements of the sequence. Seq.init creates a new sequence with a count (in this case) of the length of sequence s plus 1, and for each element in the sequence takes the first n elements in s.
Second solution:
let i s=Seq.map(fun n->Seq.take n s){0..Seq.length s}
Similar to before, except it creates a sequence from 0 to the length of s. Then takes that number of elements from s.
C# (Visual C# Interactive Compiler), 48 bytes
l=>new int[l.Count()+1].Select((_,n)=>l.Take(n))
Explanation
l=> // Function with list l as argument
new int[l.Count()+1] // A new array (int is shortest type available) of length l + 1
.Select((_,n)=>l.Take(n)) // Where every element is mapped to the first n elements of the input list, where n is the index
Common Lisp, 39 bytes
(defun f(l)`(,@(if l(f(butlast l))),l))
Explanation
(defun f(l) ) ; Define a function f
`( ) ; With the list (essentially capable of interpolation), containing:
,@ ; The value of, flattened to one level
(if l ) ; If l is not the empty list (which is the representation of nil, i.e. the only falsy value)
(f(butlast l)) ; Recurse with all of l but the tail
,l ; The value of l
Mathematica, 22 21 bytes
-1 byte thanks to Misha Lavrov!
{}~FoldList@Append~#&
Pure function. Takes a list as input and returns a list of lists as output. I believe this is the shortest possible solution.
RAD, 7 bytes
(⊂⍬),,\
This also works in Dyalog APL as a function.
How?
This works the same for both APL and RAD, given their close relation.
(⊂⍬)the empty array,prepended to,\the prefixes (which exclude the empty array.)
Canvas, 6 5 bytes
)╶[})
Outputs to the stack; Linked with a trailing raw so that's visible.
) wrap the (currently empty) stack in an array
╶[} map nothing over the prefixes of the input
) wrap the stack (the empty array and the prefixes) in an array
2 bytes without the starting empty array.
PowerShell, 65 bytes
param($a)'';$x=,0*($y=$a.count);0..--$y|%{$x[$_]=@($a[0..$_])};$x
PowerShell helpfully unrolls lists-of-lists when the default Write-Output happens at program completion, so you get one item per line. Tack on a -join',' to see the list-of-lists better, by converting the inner lists into strings.
(Ab)uses the fact that attempting to output an empty array (e.g., @()) results in no output, so an empty array input just has '' as the output, since the $a[0..$_] will result in nothing. It will also throw out some spectacular error messages.
Haskell, 20 bytes
Edit: Yet a byte shorter with a completely different scan.
An anonymous function slightly beating the trivial import.
scanr(\_->init)=<<id
- Uses
=<<for the abbreviation(scanr(\_->init)=<<id) l = scanr(\_->init) l l. - Scans a list
lfrom right to left, collecting intermediate results with the function\_->init. - That function ignores the elements scanned through (they're only used to get the right total length for the collected results), so really iterates applying
initto the initial value of the scan, which is alsol.
Jelly, 3 bytes
ṭṖƤ
How it works
ṭṖƤ Main link. Argument: A
Ƥ Map the link to the left over all non-empty(!) prefixes of A.
Ṗ Pop; remove the last element.
ṭ Tack; append A to the resulting list.
Charcoal, 6 bytes
Eθ…θκθ
Try it online! Link is to verbose version of code. Explanation:
θ Input array
E Map over elements
θ Input array
… Moulded to length
κ Current loop index
Implicitly print each array double-spaced
θ Input array
Implicitly print
It's possible at a cost of 1 byte to ask Charcoal to print an n+1-element array which includes the input as its last element, but the output is the same, although the cursor position would be different if you then went on to print something else.