P Pr Pre Pref Prefi Prefix Prefixe Prefixes

35

3

Given some finite list, return a list of all its prefixes, including an empty list, in ascending order of their length.

(Basically implementing the Haskell function inits.)

Details

  • The input list contains numbers (or another type if more convenient).
  • The output must be a list of lists.
  • The submission can, but does not have to be a function, any default I/O can be used.
  • There is a CW answer for all trivial solutions.

Example

[] -> [[]]
[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]]

flawr

Posted 2018-12-07T19:16:03.627

Reputation: 40 560

If a language does not define any types except for characters, can I take input as a string and separate the input by newlines, in the case of a full program? – NieDzejkob – 2018-12-08T20:37:50.810

@NieDzejkob I'm not sure what consensus there is for this case, but the Brainfuck answer seems to do something like that. – flawr – 2018-12-08T21:18:44.210

Can we expect the list to be null-terminated? – None – 2018-12-09T10:02:30.527

It's especially common in C/C++, main use being strings. – None – 2018-12-13T14:46:34.987

@Rogem If it is that common I think allowing it is reasonable. – flawr – 2018-12-13T14:49:41.310

Answers

17

Haskell, 20 bytes

Edit: Yet a byte shorter with a completely different scan.

An anonymous function slightly beating the trivial import.

scanr(\_->init)=<<id

Try it online!

  • Uses =<< for the abbreviation (scanr(\_->init)=<<id) l = scanr(\_->init) l l.
  • Scans a list l from 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 init to the initial value of the scan, which is also l.

Ørjan Johansen

Posted 2018-12-07T19:16:03.627

Reputation: 6 914

15

brainfuck, 21 12 bytes

-9 bytes thanks to Arnauld suggesting the separator ÿ instead of newlines

-[[<]>[.>],]

Try it online!

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

Jo King

Posted 2018-12-07T19:16:03.627

Reputation: 38 234

1This only works on BF implementations with 8-bit, unsigned, wrapping cells. – Dev – 2018-12-10T03:11:17.237

11

JavaScript (ES6), 33 bytes

a=>[b=[],...a.map(n=>b=[...b,n])]

Try it online!

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

Arnauld

Posted 2018-12-07T19:16:03.627

Reputation: 111 334

wow, that's a whole new level of code explanation, awesome job :O – Brian H. – 2018-12-10T12:54:44.577

@BrianH. Thank you! Simple tasks are good opportunities to write detailed explanations that can't be brought up in denser code. – Arnauld – 2018-12-10T13:05:25.853

Did you make it by hand? or did you get help from any weird software i've never heard about? – Brian H. – 2018-12-10T13:08:01.890

2

Just Notepad++ with some column mode editing.

– Arnauld – 2018-12-10T13:30:47.103

8

CW for all trivial entries

Clean, 19 bytes

Haskell version works in Clean too.

import StdLib
inits

Try it online!

Haskell, 22 bytes

import Data.List
inits

Try it online!

Prolog (SWI), 6 bytes

prefix

Try it online!

flawr

Posted 2018-12-07T19:16:03.627

Reputation: 40 560

So torn - to upvote or not. On the one hand, I appreciate all the built-in solutions in one place. On the other, I really dislike builtins because they're so basic... – None – 2019-01-02T20:39:45.490

6

Jelly, 3 bytes

ṭṖƤ

Try it online!

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.

Dennis

Posted 2018-12-07T19:16:03.627

Reputation: 196 637

6

Japt, 4 bytes

²£¯Y

Try it online!

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

Kamil Drakari

Posted 2018-12-07T19:16:03.627

Reputation: 3 461

6

Python 2, 32 bytes

f=lambda l:(l and f(l[:-1]))+[l]

Try it online!

ovs

Posted 2018-12-07T19:16:03.627

Reputation: 21 408

1Also works in Python 3 – ASCII-only – 2018-12-08T04:14:54.220

6

Perl 6, 13 bytes

{(),|[\,] @_}

Try it online!

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 |.

Sean

Posted 2018-12-07T19:16:03.627

Reputation: 4 136

2O_o what is even happening here – ASCII-only – 2018-12-08T04:12:35.263

1

@ASCII-only triangular reduction

– user202729 – 2018-12-08T04:33:53.490

5

R, 40 39 bytes

function(L)lapply(0:length(L),head,x=L)

Try it online!

-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.

Giuseppe

Posted 2018-12-07T19:16:03.627

Reputation: 21 077

139 using lapply – digEmAll – 2018-12-08T12:46:30.720

@digEmAll thanks! – Giuseppe – 2018-12-10T14:41:08.040

4

JavaScript, 36 bytes

a=>[...a,0].map((x,y)=>a.slice(0,y))

Try it online!

Oliver

Posted 2018-12-07T19:16:03.627

Reputation: 7 160

4

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.

LegionMammal978

Posted 2018-12-07T19:16:03.627

Reputation: 15 731

We can write the same solution more compactly as {}~FoldList@Append~#&. – Misha Lavrov – 2018-12-07T21:59:23.180

@MishaLavrov Thanks! I didn't think to use the curried 1+2-argument form like that. – LegionMammal978 – 2018-12-07T22:46:33.247

4

Husk, 2 bytes

Θḣ

Gets all the eads and then prepends Θ (in this case []):

Try it online!

(needs type annotation for empty list: Try it online!)

ბიმო

Posted 2018-12-07T19:16:03.627

Reputation: 15 345

3

J, 5 bytes

a:,<\

Try it online!

FrownyFrog

Posted 2018-12-07T19:16:03.627

Reputation: 3 112

3

PowerShell, 65 bytes

param($a)'';$x=,0*($y=$a.count);0..--$y|%{$x[$_]=@($a[0..$_])};$x

Try it online!

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.

AdmBorkBork

Posted 2018-12-07T19:16:03.627

Reputation: 41 581

Wrapping it in parens instead of assigning it saves 20 bytes. Unless you don't think that counts as returning a list of lists. I've always been fuzzy on that distinction. – Veskah – 2018-12-08T02:59:33.850

@veskah Yeah, that's almost what I had before my edit to this version. The problem with your solution or my earlier solution -- it doesn't return a list-of-lists. TIO1 vs TIO2

– AdmBorkBork – 2018-12-10T13:44:10.147

3

K (ngn/k), 8 7 bytes

1_',\0,

Try it online!

ngn

Posted 2018-12-07T19:16:03.627

Reputation: 11 449

1This is some kind of voodoo. ,\(,()), in K4. Joining enlisted null along enlisted input? howsitwork? – streetster – 2018-12-07T20:46:41.413

1@streetster () is an empty list. (,()),x prepends it to x. finally ,\ does a concat-scan. the x is omitted to form a composition. note that the trailing , is dyadic, so it's "concat", not "enlist". – ngn – 2018-12-07T21:07:00.167

1@streetster in k4 it can be a byte shorter: 1_',\0, but my parser isn't smart enough to handle this... – ngn – 2018-12-07T21:13:07.323

3

Common Lisp, 39 bytes

(defun f(l)`(,@(if l(f(butlast l))),l))

Try it online!

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

ASCII-only

Posted 2018-12-07T19:16:03.627

Reputation: 4 687

3

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)

Try it online!

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.

Try this online too!

Ciaran_McCarthy

Posted 2018-12-07T19:16:03.627

Reputation: 689

fun s->Seq.map(fun n->Seq.take n s){0..Seq.length s} saves 1 byte – Embodiment of Ignorance – 2018-12-09T06:41:24.420

3

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

Suever

Posted 2018-12-07T19:16:03.627

Reputation: 10 257

use v instead of []. And doesn't : use 1 as the default first argument? So this could be vin:"G@:)]Xh for 12 bytes. – Giuseppe – 2018-12-10T18:34:27.623

@Giuseppe Thanks! My MATL is a little rusty it seems :( – Suever – 2018-12-10T22:04:28.233

3

SWI PROLOG 22 bytes

i(X,Y):-append(X,_,Y).

styrofoam fly

Posted 2018-12-07T19:16:03.627

Reputation: 151

2

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.

Neil

Posted 2018-12-07T19:16:03.627

Reputation: 95 035

2

05AB1E, 3 bytes

η¯š

Explanation:

η    Prefixes
  š  Prepend
 ¯   Global array (empty by default)

Try it online!

Okx

Posted 2018-12-07T19:16:03.627

Reputation: 15 025

2

RAD, 7 bytes

(⊂⍬),,\

Try it online!

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.)

Zacharý

Posted 2018-12-07T19:16:03.627

Reputation: 5 710

2

Groovy, 37 bytes

{x->(0..x.size()).collect{x[0..<it]}}

Try it online!

GolfIsAGoodWalkSpoilt

Posted 2018-12-07T19:16:03.627

Reputation: 101

{it.inits().reverse()} will work once we get groovy 2.5 on TIO – ASCII-only – 2019-01-02T02:08:16.083

2

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))

Try it online!

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++));}

Try it online

ბიმო

Posted 2018-12-07T19:16:03.627

Reputation: 15 345

You can golf it to 77 bytes by just using java.util.stream.IntStream directly and drop the import. – Kevin Cruijssen – 2018-12-10T07:44:25.090

@KevinCruijssen: Oh thanks! I didn't even know that this was possible, that's certainly helpful (at least for golfing purposes). – ბიმო – 2018-12-10T14:19:26.637

x->{for(int i=0;i<=x.size();)System.out.println(x.subList(0,i++));} (67 bytes). This prints instead of using streams. Printing is usually the shortest way to output complex structures. – Olivier Grégoire – 2018-12-10T17:01:03.373

@OlivierGrégoire: In that case you can probably get away with System.out.print since the output is still unambiguous. – ბიმო – 2018-12-10T17:55:14.380

@BMO Indeed, that would be possible! – Olivier Grégoire – 2018-12-10T23:28:03.113

2

Japt, 5 bytes

Êò@¯Y

Try it online!

Oliver

Posted 2018-12-07T19:16:03.627

Reputation: 7 160

2

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.

,>-[+>,]<[-<]<<++++++++++[[<]>[.>]>[-<+>]<]

Try it online!

user202729

Posted 2018-12-07T19:16:03.627

Reputation: 14 620

Another answer outgolfed me by more than a half, because I didn't think about printing output while reading. Of course that method won't work with printing increasing suffixes. – user202729 – 2018-12-08T09:58:41.153

40 bytes with some rearranging – Jo King – 2018-12-08T10:19:06.730

2

C# (Visual C# Interactive Compiler), 39 bytes

x=>x.Select((_,i)=>x.Take(i)).Append(x)

Try it online!

dana

Posted 2018-12-07T19:16:03.627

Reputation: 2 541

You need to include the using System.Linq; in your bytecount. And it seems some of your output logic is in your outputting of the arrays. Because empty array just returns empty array. – LiefdeWen – 2018-12-11T09:51:58.413

@LiefdeWen - my understanding is that since this interpreter includes a reference to System.Linq, I don't have to include this in the byte count. My submission would be considered a different language than say .NET Core. https://github.com/dotnet/roslyn/wiki/C%23-Interactive-Walkthrough - You mention printing which is a separate issue, I'd like to get clarity on this first.

– dana – 2018-12-11T10:35:52.957

With regards to printing, here is a version that basically dumps the result to the console - https://tio.run/##XY29CsIwGEX3PEXGBGKhtVt/wEHBTdCtFInxKwZrLEmqhdJnj2kV1I733Hs5wiyEkW7TKpFu16q9geanGlKpbM5@wbzMc1zhzHVZ3gV7qEFYQo5M0jEf@BWIpDRYNQ2oM@moSxDyr6IsSmzBWIMzrOCJPwz1CH9zP7C/GEczELKILVk8n3kWsdDTwdtQddfAxYU8uJ6UfvVW08m20/5FKjIiShM0uBc - not as pretty for sure! The question I have is when is it acceptable to use Array vs IList vs IEnumerable.

– dana – 2018-12-11T10:59:57.137

2

F# (Mono), 45 bytes

fun x->List.mapi(fun i y->List.take i x)x@[x]

Try it online!

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.

dana

Posted 2018-12-07T19:16:03.627

Reputation: 2 541

2

Ruby, 31 29 bytes

->a{[a*i=0]+a.map{a[0,i+=1]}}

Try it online!

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
  }
}

Asone Tuhid

Posted 2018-12-07T19:16:03.627

Reputation: 1 944

2

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);}

Try it online!

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.
}

user77406

Posted 2018-12-07T19:16:03.627

Reputation:

@ceilingcat Thanks, will edit it in later when I get back onto a PC. – None – 2019-01-02T20:34:40.833

2

Brachylog, 9 bytes

a₀ᶠ~b.hĖ∧

Try it online!

Explanation

a₀ᶠ           Find all prefixes of the input
   ~b         Add an element at the beginning of that list of prefixes
      hĖ      This element is the empty list
     .  ∧     (the list with the additional empty list is the output)

Fatalize

Posted 2018-12-07T19:16:03.627

Reputation: 32 976

2

05AB1E, 8 bytes

That was my first succesfull golf! Thanks for being such a nice community!

)UŒ¹g£Xš

Try it online!

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       

krinistof

Posted 2018-12-07T19:16:03.627

Reputation: 431

1

C# (Visual C# Interactive Compiler), 48 bytes

l=>new int[l.Count()+1].Select((_,n)=>l.Take(n))

Try it online!

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

ASCII-only

Posted 2018-12-07T19:16:03.627

Reputation: 4 687

1

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.

cyclaminist

Posted 2018-12-07T19:16:03.627

Reputation: 191

1

Pari/GP, 23 bytes

a->[a[1..n]|n<-[0..#a]]

Try it online!

alephalpha

Posted 2018-12-07T19:16:03.627

Reputation: 23 988

1

Pip, 16 bytes

{h@<a}M,1+#(h:a)

Try it online!

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)

ASCII-only

Posted 2018-12-07T19:16:03.627

Reputation: 4 687

Similar approach, 22 – ASCII-only – 2018-12-08T05:02:46.083

1

Powershell, 24 bytes

,@()
$args|%{,($x+=,$_)}

Explanation:

  1. The trivial accumulator wrapped to array by unary ,.
  2. 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

mazzy

Posted 2018-12-07T19:16:03.627

Reputation: 4 832

1

Ruby, 34 31 bytes

->l{(0..l.size).map{|i|l[0,i]}}

Try it online!

Thanks @ConorO'Brien!

Eric Duminil

Posted 2018-12-07T19:16:03.627

Reputation: 701

1You can golf this a bit like so: ->l{(0..l.size).map{|i|l[0,i]}}, using [0,i] for indexing instead of .first i – Conor O'Brien – 2018-12-10T23:25:09.530

@ConorO'Brien: Thanks a lot! 1 fewer byte than Python now :D – Eric Duminil – 2018-12-11T08:24:22.230

1

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#.

cat

Posted 2018-12-07T19:16:03.627

Reputation: 4 989

1

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.

Terjerber

Posted 2018-12-07T19:16:03.627

Reputation: 51

1

Scala, 21 bytes

_.inits.toSeq.reverse

Try it online!

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.

Brian McCutchon

Posted 2018-12-07T19:16:03.627

Reputation: 503

Not sure if this is valid since this is a function, not a lambda (and you're excluding the function declaration part). Hmmmmmm – ASCII-only – 2019-01-02T02:05:01.470

@ASCII-only This is Scala's underscore shorthand syntax. It's basically a lambda. Compare to Haskell's sections. See also https://codegolf.meta.stackexchange.com/questions/11223/untyped-functions-in-static-languages

– Brian McCutchon – 2019-01-02T06:24:56.530

Yes, but it can not be assigned to a variable (lambda function). On the other hand, {_.inits.toSeq.reverse} can.

– ASCII-only – 2019-01-02T06:27:16.750

@ASCII-only Nope, the braces are not needed (though you do need to use val instead of var for some reason): https://tio.run/##JYq9CgIxEAb7e4qvTCAE/KkEBXutLEWOeO7BStiLyXII4rPHqN3MMGUIMdTpeqdBcQwsoKeS3Ar2KeHVAXOIGDc40ePcX7Dd/ehvTWvvWViL16k1n2mmXKgCKbNoFDOaAxc1C4elw8phbW17v8127/oB

– Brian McCutchon – 2019-01-02T06:38:12.147

Oh wait, you can define functions like variables, nvm – ASCII-only – 2019-01-02T06:39:41.433

1

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)

Kevin Cruijssen

Posted 2018-12-07T19:16:03.627

Reputation: 67 575

1hÅ_╡]x saves one byte. For doing test suites, just add one input per line, and the code will be executed separately for each input. Check my answer for an example. I should describe that feature better in the docs. – maxb – 2018-12-10T14:56:10.413

@maxb Thanks, that simplifies the test suite a lot. Need to remember that. And thanks for the golf! – Kevin Cruijssen – 2018-12-10T15:00:16.893

1

D, 70 bytes (31 imports, 39 expression)

import std.algorithm,std.range;
alias prefixes = t=>(t.length+1).iota.map!(i=>t.take(i));

Try it online!

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?

FeepingCreature

Posted 2018-12-07T19:16:03.627

Reputation: 111

1I don't program in D, but I think you don't count the alias prefixes. Python lambdas are very similar and they act in that way. – Post Rock Garf Hunter – 2018-12-10T15:39:53.677

1There is one problem though. I'm pretty sure you need to count the imports. – Zacharý – 2018-12-10T18:32:21.720

Wait, none of the others use standard library routines? edit: I feel it'd be kind of silly to make code size dependent on what standard definitions the language chooses to make available by default. That seems more of a judgment of a language's module system than its expressivity. – FeepingCreature – 2018-12-10T21:33:44.437

Though fair enough, the Java example seems to count module names. Bleh. edit: Though it seems pretty nonsensical to count the imports and not the alias, and in any case what about the void main()... seems like it'd just become a boilerplate size contest, rather than expression size. – FeepingCreature – 2018-12-10T21:39:28.750

You don't have to count the main function nor the stdio import (which is only used in the main function), but importing algorithm and range contributes to the score. – Dennis – 2018-12-10T22:52:48.423

Alright.. feels like I'm mostly counting letters in names, but sure. I think it seems so arbitrary because I'm basically discounting pieces in the middle of the code. – FeepingCreature – 2018-12-11T05:26:21.083

One would count this as if it was import std.algorithm,std.range;t=>(t.length+1).iota.map!(i=>t.take(i)) – Zacharý – 2018-12-11T18:34:01.417

1So, in response to my above comment: this would count as 70 bytes. (Note: a golf was applied changing two imports to a single import) – Zacharý – 2018-12-11T18:38:42.087

1

MathGolf, 7 bytes

hæ_ï<\]

Try it online!

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

maxb

Posted 2018-12-07T19:16:03.627

Reputation: 5 754

Nice 7 byte alternative to my 7-byter I found an hour ago. :) Actually, I see I can golf mine to 6 bytes by changing { to Å. Thanks for the implicit golf. Now I just need to fix the test suite somehow..

– Kevin Cruijssen – 2018-12-10T14:49:04.630

You could save a byte for that one by replacing { with Å and removing the }. MathGolf has 1-byte literals for blocks of size up to 8 bytes. – maxb – 2018-12-10T14:53:11.663

Just edited my comment when I realized that. Just not sure how to fix the test suite.. – Kevin Cruijssen – 2018-12-10T14:53:56.443

1

Clojure, 21 bytes

#(reductions conj[]%)

NikoNyrh

Posted 2018-12-07T19:16:03.627

Reputation: 2 361

1

Gambit Scheme (gsi), 77 72 bytes

(define(p z)(if(pair?(car z))(p(cons(reverse(cdr(reverse(car z))))z))z))

Try it online!

First time using Scheme. It's a function that takes a wrapped list ((list (list 1 2 3 4))) as an argument.

Comrade SparklePony

Posted 2018-12-07T19:16:03.627

Reputation: 5 784

I think you might want to reverse that if test. – Ørjan Johansen – 2018-12-12T20:00:21.090

@ØrjanJohansen Yep. Thank you. – Comrade SparklePony – 2018-12-12T20:23:03.650

0

Haskell, 27 bytes

i[]=[[]]
i l=i(init l)++[l]

Try it online!

flawr

Posted 2018-12-07T19:16:03.627

Reputation: 40 560

0

Canvas, 6 5 bytes

)╶[})

Try it here!

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.

dzaima

Posted 2018-12-07T19:16:03.627

Reputation: 19 048

0

MY, 7 bytes

ωωι0;↑←

Try it online!

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

Zacharý

Posted 2018-12-07T19:16:03.627

Reputation: 5 710

0

Tcl, 81 bytes

set i -1
set a {{}}
foreach _ $argv {lappend a [lrange $argv 0 [incr i]]}
puts $a

Try it online!

ASCII-only

Posted 2018-12-07T19:16:03.627

Reputation: 4 687

0

Attache, 13 bytes

{_[0...0:#_]}

Try it online!

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

Conor O'Brien

Posted 2018-12-07T19:16:03.627

Reputation: 36 228

0

Red, 76 bytes

func[b][a: copy[[]]c: b until[append/only a copy/part b c: next c tail? c]a]

Try it online!

Galen Ivanov

Posted 2018-12-07T19:16:03.627

Reputation: 13 815

0

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
    }
}

Try it online!

snail_

Posted 2018-12-07T19:16:03.627

Reputation: 1 982

0

Pushy, 7 bytes

1@$O_vI

Try it online!

FlipTack

Posted 2018-12-07T19:16:03.627

Reputation: 13 242

0

Tcl, 65 bytes

proc P {L J\ {{}}} {lmap e $L {lappend J [lappend K $e]}
list $J}

Try it online!

sergiol

Posted 2018-12-07T19:16:03.627

Reputation: 3 055

0

Z80Golf, 18 bytes

00000000: 2511 00ff 1b1a ffa7 20fa cd03 802b 7730  %....... ....+w0
00000010: f076                                     .v

Try it online!

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

NieDzejkob

Posted 2018-12-07T19:16:03.627

Reputation: 4 630

0

Forth (gforth), 57 bytes

: x here 0 begin 2dup type cr 1+ key dup c, 5 < until ; x

Try it online!

Takes bytes through STDIN and prints a series of prefixes, each terminated by a newline.

NieDzejkob

Posted 2018-12-07T19:16:03.627

Reputation: 4 630

0

str, 6 bytes

e;:dno

Try it online!

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)

Conor O'Brien

Posted 2018-12-07T19:16:03.627

Reputation: 36 228

0

Perl 5 + -a, 24 bytes

say"@F[0..$_]"for-1..$#F

Try it online!

Dom Hastings

Posted 2018-12-07T19:16:03.627

Reputation: 16 415

0

Actually, 13 bytes

;╗ru⌠╜H⌡M[]@o

Try it online!

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

Mego

Posted 2018-12-07T19:16:03.627

Reputation: 32 998

0

Elixir, 37 bytes

fn x->Enum.scan [[]|x],&(&2++[&1])end

Try it online!

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.

Kirill L.

Posted 2018-12-07T19:16:03.627

Reputation: 6 693

0

APL (Dyalog Unicode), 12 bytes

(0,∘⍳∘≢⊢)↑¨⊂

Try it online!

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.

J. Sallé

Posted 2018-12-07T19:16:03.627

Reputation: 3 233

0

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 ]

philcolbourn

Posted 2018-12-07T19:16:03.627

Reputation: 501

0

Reticular, 60 bytes

Bql:D=:D`:E=l[:D`@d]~*[:E`b@qM[$]:D`:E`-*:E`1-:E=]:D`1+*lbo;

Try it online!

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.

Wisław

Posted 2018-12-07T19:16:03.627

Reputation: 554