title: Implement Takewhile

text:
# Question
Title: Implement Takewhile
## Introduction and Credit

Today without a fancy prelude: Please implement `takewhile`.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

## Specification

### Input

The input will be a list (or your language's equivalent concept) of positive integers.

### Output

The output should be a list (or your language's equivalent concept) of positive integers.

### What to do?

Your task is to implement `takewhile` (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (`takewhile`).

### Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. `[14,42,2]` may not become `[42,14]`.

The empty list is a valid in- and output.

### Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

## Test Vectors

```
[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]

```

### Step-by-Step Example

```
Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]

```

# Answer
## Mathematica, 18 bytes

```
#~TakeWhile~EvenQ&

```

Another glorious built-in that is beaten by a factor of 3 by golfing languages without the built-in...
> 29 votes

# Answer
## Haskell, 13 bytes

```
fst.span even

```

`span` splits the input list into a pair of lists just before the first element where the predicate (-\> `even`) is false. `fst` takes the first element of the pair.

Alternative version, 13 bytes:

```
fst.break odd

```

`break` is the opposite of `span`, i.e. it splits the list at the first element where the predicate is true.

Of course there's also

```
takeWhile even

```

but that's 14 bytes.
> 28 votes

# Answer
# MATL, 6 bytes

```
toYs~)

```

**Try it online!**

### Explanation

```
t    % Input array implicitly. Duplicate
o    % Parity of each entry. Gives 0 for even entries, 1 for odd
Ys   % Cumulative sum
~    % Logical negate. Gives true for the first run of even entries, and then false
)    % Use this as logical index into the original array. Implicitly display

```
> 25 votes

# Answer
# Hexagony, 19

```
2.}<@>%?<{>$"/\M!8;

```

Readable:

```
  2 . }
 < @ > %
? < { > $
 " / \ M
  ! 8 ;

```

Try it online!

This can probably be golfed by a byte or two, but that might require some truly ingenious layout, that might be more easily found via brute force (even if it might take rather long to find it).

### High level explanation

The program mostly follows this pseudocode:

```
while (read number is not zero)
{
    if (number is even)
        print number;
}

```

Which abuses how Hexagony tries to read a number once STDIN is empty (it returns a zero). Big thanks to Martin for help with coming up with this approach.

### Full Explanation

I still haven't fiddled around with Mono to get Timwi's fantastic esoteric IDE running, so I've leant on Martin to provide me with some helpful pretty pictures!

First, a little primer on basic control flow in Hexagony. The first instruction pointer (IP), which is the only one used in this program, starts at the top left of the hexagonal source code, and begins moving towards the right. Whenever the IP leaves the edge of the hexagon, it moves `side_length - 1` rows towards the middle of the hexagon. Since this program uses a side length three hexagon, the IP will always be moving two rows when this happens. The only exception is if it moves off of the middle row, where it conditionally moves towards the top or bottom of the hexagon, depending on the value of the current memory edge.

Now a bit about conditionals. The only conditionals in Hexagony for control flow are `>`, `<` and the middle edge of the hexagon. These all follow a constant rule: if the value on the current memory edge is zero or negative control flow moves left and if is positive the control flows right. The greater than and less than brackets redirect the IP at sixty degree angles, while the edge of the hexagon controls to which row the IP jumps.

Hexagony also has a special memory model, where all data is stored on the edges of an infinite hexagonal grid. This program only uses three edges: one to store a two, one for the currently read number, and one for the number modulo two. It looks something like:

```
Mod  \ / Input
      |
      2

```

I'm not going to carefully explain where we are in memory at each point during the explanation of the program, so come back here if you get confused by where we are in memory.

With all of that out of the way, the actual explanation can begin. First, we populate the "2" edge in memory with a 2, then we execute a no-op and move the memory pointer to the right (`2.}`).

Next, we begin the main program loop. We read the first number from STDIN and then we hit a conditional (`?<`). If there are no numbers left in STDIN, this reads a zero into the current memory edge, so we turn left onto the `@`, which ends the program. Otherwise, we bounce off a mirror, move the memory pointer backwards and to the left, wrap around the hexagon to calculate the remainder of dividing the input by 2 and then hit another conditional (`/"%>`).

If the remainder was one (i.e. the number was odd), we turn right following the blue path above starting by executing the no-op again, then we wrap around to the bottom of the hexagon, multiply the current edge by 10 and then add eight, bounce off a couple mirrors, do the same multiplication and addition again, getting 188 on the current edge, wrapping back around to the top of the hexagon, executing the no-op again, and finally ending the program (`.8/\8.@`). This convoluted result was a happy accident, I originally had written a much simpler bit of logic, but noticed that I could remove it in favour of the no-op, which I thought was more in the spirit of Hexagony.

If the remainder was zero we instead turn left following the red path, above. This causes us to move the memory pointer to the left, and then print the value there (the input value) as a number. The mirror we encounter acts as a no-op because of the direction we are moving (`{/!`). Then we hit the edge of the hexagon which acts a conditional with only one outcome, as the input value from before was already tested to be positive, so we always move towards the right (if you imagine yourself facing in the direction of the IP). We then multiple the input by 10 and add two, only to change direction, wrap around and overwite the new value with the ascii value of the capital letter M, 77. Then we hit some mirrors, and exit over the edge of the middle of the hexagon with a trampoline (`2<M\>$`). Since 77 is positive, we move right towards the bottom of the hexagon and because of the trampoline skip the first instruction (`!`). We then multiply the current memory edge by 10 and add 8, getting 778. We then output this value mod 256 (10) as an ASCII character, which happens to be newline. Finally we exit the hexagon and wrap back around to the first `?` which overrides the 778 with the next input value.
> 14 votes

# Answer
## ed, 13

```
/[13579]$/,$d

```

Because *real* programmers use The Standard Text Editor.

Takes input as one integer on each line; outputs in the same format.

This simply finds the first odd number (number ending in an odd digit) and deletes from that line until the end of the file.
> 11 votes

# Answer
# Pyth, ~~13~~ ~~9~~ 7 bytes

```
uPWs%R2

```

Credits to @FryAmTheEggman for 2 (quite tricky) bytes!

Explanation:

```
u       Q    keep applying to input until invariant:
 PW          drop last element if...
   s%R2G     ...any one is odd, G is the argument originally given the value of input

```

Test it here.
> 10 votes

# Answer
# Jelly, 5 bytes

```
Ḃœp⁸Ḣ

```

Try it online! or verify all test cases.

### How it works

```
Ḃœp⁸Ḣ  Main link. Argument: A (array)

Ḃ      Bit; yield 1 for odd integers, 0 for even ones.
   ⁸   Yield A.
 œp    Partition A, splitting at 1's in the bit array.
       This yields a 2D array of runs of even integers.
    Ḣ  Head; extract the first chunk.

```
> 9 votes

# Answer
# Python 2, ~~43~~ 42 bytes

```
def f(x):
 while"1'"in`map(bin,x)`:x.pop()

```

The function modifies its argument in place.

*Thanks to @xnor for golfing off a byte in a really clever way!*

Test it on Ideone.
> 8 votes

# Answer
## Clojure, 21 bytes

```
#(take-while even? %)

```

Clojure is kinda nearly competing at last! (thanks to the task being a built-in) See it online https://ideone.com/BEKmez
> 7 votes

# Answer
# Python, ~~45~~ 44 bytes

```
f=lambda x:x and~x[0]%2*x and x[:1]+f(x[1:])

```

Test it on Ideone.
> 6 votes

# Answer
# Brainf\***, 263 bytes

I took a little snippet from here

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

```

I'd give an explanation but even I don't have a clue how this works anymore.

Expects input as space-seperated numbers (eg `2 432 1`)
> 6 votes

# Answer
## 05AB1E, ~~8~~ 7 bytes

```
[DÉO_#¨

```

**Explanation**

```
[        # infinite loop start
 DÉO     # count odd numbers
    _    # push negative bool (turning 0->1, X->0)
     #   # if true (no odd numbers exist), break out of loop and implicitly print
      ¨  # else, remove last element from list

```

Try it online

**Previous 8 byte solution**

```
vyÈiyˆëq

```

**Explanation**

```
v         # for each y in input
 yÈi      # if y is even
    yˆ    # push y to global array
      ëq  # else terminate program
          # implicitly print global array

```

Try it online
> 5 votes

# Answer
## Labyrinth, 14 bytes

```
?:
"`#
"@%
\!;

```

Input and output are linefeed-separated lists (although in principle, the input could use any non-digit separator).

Try it online!

This is probably the most compact Labyrinth program I've ever written.

Interestingly, `takewhile(odd)` is lot simpler:

```
?:#
" %
\!/

```

### Explanation

The usual Labyrinth primer:

* The memory model is a stack (there's actually two, but we'll only need one for this program), which holds arbitrary-precision integers and initially holds an (implicit) infinite number of zeros.
* There are no control flow instructions. Instead, the movement of the instruction pointer (IP) is determinated by the layout of the code (spaces are considered "walls" and cannot be traversed by the IP). *Normally*, the code is supposed to resemble a maze, where the IP follows straight corridors and bends, but whenever it reaches a junction, this acts as a conditional where the IP's new direction is determined based on the current state. The rules for choosing a direction boil down to this: if the top of the stack is zero, the IP keeps moving forward; if the top is positive, the IP turns right; if the top is negative the IP turns left. If one of these directions is blocked by a wall, the IP takes the opposite direction instead. This means that programs *without* clear corridors are usually incredibly tough to work with, because every single command would act as a junction. The fact that this worked out in this case is a bit of a miracle.
* The IP starts at the first non-space character in reading order (`?` in this case), moving east.

The main flow through the program is a single loop around the perimeter:

```
>v
^>v
^@v
^<<

```

As it happens, we know that the top of the stack is zero after `!` and `"` so that the IP is guaranteed not to turn towards the centre. ``` and `%` on the other hand are used as conditionals where the IP might move towards the centre such that `@` terminates the program, or it might keep moving around the perimeter.

Let's look at the code in the loop:

```
?   Read decimal integer N from STDIN, or 0 at EOF.
:   Duplicate. Since this is just a corner, the IP always turns south.
`   Negate the copy of the input (i.e. multiply by 1). At EOF, the result
    is still zero and the IP keeps moving south into the @. Otherwise, the
    top of the stack is now negative, and the IP turns east.
#   Push the stack depth (i.e. 2). Again, this is a corner, and the IP
    is forced to turn south.
%   Computer (-N % 2), which is identical to (N % 2) to determine the
    parity of the input. If input was odd, this gives 1, and the IP turns
    west into the @. Otherwise, the result is 0 and the IP keeps moving
    south, continuing the loop.
;   Discard the 0. This is a corner, so the IP is forced to turn west.
!   Print (and discard) N. The top of the stack is now one of the implicit
    zeros at the bottom, so the IP keeps moving west.
\   Print a linefeed. The IP is forced to turn north in the corner.
""  Two no-ops. The top of the stack is still zero, so the IP keeps moving north.

```

And then the loop starts over.

That raises the question why `takewhile(odd)` is so much simpler. There's two reasons:

* Since EOF is returned as `0` (which is even), we don't need a separate EOF check. The list would be cut off at that point anyway.
* Now we want to terminate when `N % 2` is `0` (as opposed to `1`), which means instead of conditional control flow we can simply divide the other copy `N` by `N % 2`: if the input is odd, that just leaves `N` and we even got rid of the `N % 2` (so we don't need `;`), but if the input is even, that simply terminates the program with a (silent) division-by-zero error.

Hence, the other code is a simple loop that doesn't allow for any branching at all.
> 5 votes

# Answer
## R, 25 bytes

```
x=scan()
x[!cumsum(x%%2)]

```

Or equivalently

```
(y=scan())[!cumsum(y%%2)]

```
> 5 votes

# Answer
## Pyth, 7 bytes

```
<x%R2Q1

```

Try it here!

What I attempted to do in Pyke but index is broken in that atm
> 4 votes

# Answer
# Racket, 22 bytes

```
(λ(n)(takef n even?))

```

The `λ` character is counted as 2 bytes.

I haven't seen Racket used before in any of the code golfing answers I've seen, so I had to do it at least once!
> 4 votes

# Answer
# Perl 5 + Perligata, 173 bytes

145 bytes, plus 28 for `-MLingua::Romana::Perligata`

Use as `perl -MLingua::Romana::Perligata foo.pl`; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata, released two days ago; I don't know whether it works with Perligata version 0.50.

```
huic vestibulo perlegementum da.his _ scindementa da.per in his fac sic
si recidementum hoc tum II fac sic I exi cis
hoc tum _ egresso scribe
cis

```

---

Obviously this is clear as a bell. In case it's not, run it with `-MLingua::Romana::Perligata=converte` instead of `-MLingua::Romana::Perligata`, and `perl` will, instead of running the script, output a translation into regular Perl:

```
 $_ = Lingua::Romana::Perligata::getline (*STDIN );
 @_ = split ( '_');
for $_ (@_) {if ( ($_ % 2)) {exit ( 1)}
;
print (STDOUT $_, '_')}

```

For a token-by-token analysis, use `-MLingua::Romana::Perligata=discribe`.

---

Golfing notes:

* It seems from the documentation that `ultimus si recidementum hoc tum II fac.` would work instead of `si recidementum hoc tum II fac sic ultimus cis`, saving 7 bytes. But it doesn't (it gives a "iussa absentia" error).
* Undocumented (but unsurprising), you don't need a space after `.`.
* (Also unsurprising,) `scinde` doesn't need a second argument, and uses `hoc`. Alas, `exi` needs an argument.
* Instead of `huic vestibulo perlegementum da`, I tried `-pMLingua::Romana::Perligata`, but couldn't get it to work.

---

Just for kicks (although this whole answer was just for kicks):

* After cleaning it up to `Huic vestibulo perlegementum da. His lacunam scindementa da. Per in his fac sic si recidementum hoc tum II fac sic I exi cis. Hoc tum lacunam egresso scribe cis.`, Google Translate gives `This court perlegementum grant. His gap scindementa grant. 2 By that time, do so in the following 1, Go out and do so if recidementum on this side. This was the gap as soon as write on this side.`.
> 4 votes

# Answer
# Perl 6, 14 bytes

```
{|$_,1...^*%2}

```

Try it online!

Finally, a use for a neat trick I found involving `...`. This is an anonymous code block that basically filters the list until it reaches an element that succeeds in the condition `*%2` i.e. odd. Then we return the list excluding the last element. Since an element has to pass the condition at some point, otherwise it attempts to extrapolate off the end of the list, we append a `1` to the input list.

Note this isn't the intended use for the sequence operator `...`, which is usually used to create sequences based off several parameters. We're using the behaviour that the end condition is checked against the starting elements as well, and will stop even before any new elements are generated.

### Explanation:

```
{            }  # Anonymous code block
 |$_,1          # Using the input list appended with 1
      ...       # Take up to
          *%2   # The element that is odd
         ^      # And exclude the last element

```
> 4 votes

# Answer
# Brachylog, ~~19~~ 16 bytes

```
~~hH:2%0,?b&~b.hH;[].~~

s.:Mc?,.:{:2%0}a

```

### Explanation

```
s.                 Output is an ordered subset of Input
  :Mc?,            The concatenation of Output with a list M is Input
       .:{:2%0}a   All elements of Output are even

```

Today I learnt a neat trick (which was used in the 19 bytes answer): `~b.hH` is shorter than `:[H]rc.` to append an element at the beginning of a list. The first one means *"Output is the result with an extra item at the beginning, and the first item of the Output is `H`"*, whereas the other one is straightforwardly *"Output is the concatenation of `[[H], Result]`".*
> 3 votes

# Answer
## Retina, 17 bytes

```
 ?\d*[13579]\b.*

```

The trailing linefeed is significant. Input and output are space-separated lists.

Try it online!

This is a simple regex substitution, it matches the first odd number (i.e. a number ending in an odd digit), and if possible the space preceding it as well as everything after it and replaces it with an empty string, i.e. all elements from there onward are removed from the input.

As Leaky Nun points out, taking the list in binary, we can save 6 bytes, but it seems a bit cheaty, so I'll probably continue counting the decimal version:

```
 ?\d*1\b.*

```
> 3 votes

# Answer
# Dyalog APL, 11 bytes

```
{⍵/⍨∧\~2|⍵}

```

`2|` division remainder from dividing with 2

`~` negate

`∧\` AND-scan (turns off from first 0)

`/⍨` select where
> 3 votes

# Answer
# J, 10 bytes

```
{.~2&|i.1:

```

## Explanation

```
{.~2&|i.1:  Input: s
   2&|      Take each value in s mod 2
      i.1:  Find the index of the first 1
{.~         Take that many values from s and return

```
> 3 votes

# Answer
# CJam, 11 bytes

*Thanks to @Dennis for two corrections and one byte off!*

```
{1+_2f%1#<}

```

This is a code block (equivalent to a function; allowed by default) that expects the input array on the stack, and leaves the output array on the stack.

**Try it online!**

### Explanation

```
{         }    e# define code block
 1+            e# attach 1 at the end of the array
   _           e# duplicate
    2f%        e# modulo 2 of each entry
       1#      e# find index of first occurrence of 1
         <     e# slice before

```
> 3 votes

# Answer
## JavaScript (Firefox 30-57), 30 bytes

```
a=>[for(x of a)if(!(a|=x&1))x]

```
> 3 votes

# Answer
## Python, 41 bytes

```
lambda l:l[:[x%2for x in l+[1]].index(1)]

```

Truncates `l` up to the index of the first occurrence of an odd number. The index is found by looking for a `1` in the values modulo `2`. To guard against no odd number being found, a `1` is put on the end.
> 3 votes

# Answer
## C#, 50 bytes

```
int[]f(int[]a)=>(a.TakeWhile(x=>x%2<1).ToArray());

```
> 3 votes

# Answer
# JavaScript, ~~27~~ 25 bytes

```
a=>a.filter(v=>a=a&&~v%2)

```

The filer expression repeatedly assigns to `a` and uses the value of `a` as a filter predicate. `a` holds either the initial array value (always truthy) or the boolean of whether only even values have been seen. When `a` turns `false` (i.e., an odd number appears), then subsequent runs of the `a = a && ...` logical AND operation short cirucits, and we use `false` for the rest of the run.

The bitwise NOT `~v` turns even numbers to odd and vice versa, so `~v%2` returns a truthy value for even input and falsy values for odd input.
> 3 votes

# Answer
# SML, 44 bytes

> an assignment at my university functional programming course

Yay, functional programming! So as an assignment solution, this would probably look like this:

```
(* 'a takeWhile : ('a -> bool) -> 'a list -> 'a list *)
fun takeWhile p nil     = nil
  | takeWhile p (x::xr) = if p x then x :: takeWhile p xr else nil

(* takeWhileEven : int list -> int list *)
val takeWhileEven = takeWhile (fn x => x mod 2 = 0)

```

which can be golfed to

```
fun t[]=[]|t($ :: &)=if$mod 2=0then$ ::t&else[]

```

However using `foldr` is 3 bytes shorter:

```
foldr(fn($,r)=>if$mod 2=0then$ ::r else[])[]

```
> 3 votes

# Answer
# , 13 bytes

```
íä*[13579]¾.*

```

Try it online!

Explanation:

```
í              "search for, on every line
 ä*            "Any number of digits
   [13579]     "Followed by an odd digit
          ¾    "Then the end of a word,
           .*  "Followed by anything
               "(implicit) and replace it with nothing.

```

Conveniently, the same code works to verify all test-cases simultaneously.
> 2 votes

# Answer
## Pyke, 8 bytes

```
0+2L%fhO

```

Interpreter fixed, use other links

Uses Dennis' method except my split\_at function includes the change - probably a bug

### Or with bugfix, 7 bytes

```
2L%1R@<

```

Try it here!

```
2L%     -   map(%2, input)
   1R@  -  ^.index(1)
      < - input[:^]

```

Or after 2nd bugfix, 6 bytes

```
2L%fhO

```

Try it here!

Explanation:

```
2L%    -   map(%2, input)
   f   -  split_at(input, ^)
    hO - ^[0][:-1]

```
> 2 votes

# Answer
# Ruby, 25 bytes

```
->a{a.take_while &:even?}

```

I think I lose...
> 2 votes

# Answer
## Python 3, 59 bytes

```
def f(l):
 L=[]
 for x in l:
  if x%2:break
  L+=x,
 return L

```

Can ~~surely~~ probably be golfed more.

Thanks to everyone who commented :D
> 2 votes

# Answer
# JavaScript, 40 bytes

`a=>[...a,1].slice(0,a.findIndex(n=>n%2))`

### How it works

1) Take input array `a` and add a `1` to the end

2) Find the index of the first odd integer in the array

3) Return a subset of the array from index 0 (inclusive) to the odd integer's index (exclusive)
> 2 votes

# Answer
# Forth, 114 bytes

Forth doesn't really have lists. The parameters must be pushed onto the stack in reverse order, as is typical in Forth. The result will be left on the stack in the same order. This doesn't work on Ideone for some reason, but it works on repl. The new line is required to remove ambiguity of some sort?

```
: D DEPTH ;
: f D IF 1 D 1 DO D 1- ROLL LOOP D 0 DO I PICK 2 MOD IF D I LEAVE THEN LOOP
DO I ROLL DROP LOOP THEN ;

```

**Try it online**

Ungolfed, with comments:

```
: f DEPTH IF                                ( if stack not empty )
        1 DEPTH 1 DO DEPTH 1- ROLL LOOP     ( put 1 on bottom of stack )
        DEPTH 0 DO                          ( loop over entire stack )
            I PICK 2 MOD IF                 ( if stack[i] is odd )
                DEPTH I LEAVE               ( put range and exit loop )
            THEN
        LOOP
        DO I ROLL                           ( roll eyes )
            DROP
        LOOP                                ( iterate that range and remove )
    THEN
;

```

This program (my previous attempt) prints the results until it hits an odd number. Everything remaining (not taken) will be left on the stack.

```
: f DEPTH IF BEGIN DUP 2 MOD DUP 1- IF SWAP . THEN UNTIL THEN ;

```

*Fails if only even integers*
> 2 votes

# Answer
# GolfScript, 11 bytes

This is a full GolfScript program that reads a stringified GolfScript array literal (e.g. `[28 14 7 0]`) and prints out the same array with the first odd element and everything after it removed:

```
~1\{~&.},p;

```

**Try it online.** (Also: Extended version with test harness.)

De-golfed version with comments:

```
~     # evaluate input
1\    # push the number 1 onto the stack and move it under then input array
{     # start of loop body
  ~   #  bitwise negate the input number (making odd numbers even and vice versa)
  &   #  take bitwise AND of input and the saved number (0 or 1) on stack
  .   #  duplicate result; filter loop will pop off the duplicate
},    # run loop above over input array, select elements for which it returns true
p     # stringify and print filtered array
;     # pop the number 0/1 off the stack

```

This solution is based on the GolfScript `{ },` filter operator, which runs the contents of the code block on each element of an array, and selects the elements of the array for which the code in the block returns a true (i.e. non-zero) value on top of the stack.

Thus, for example, `{1&},` would select all odd numbers in an array, and `{~1&},` would select all even numbers. The challenge, then, is to make a filter that selects even numbers *until it finds the first odd one*, and thereafter selects no numbers at all.

The solution I used is to replace the constant bit-mask `1` (used to extract the lowest bit of each input number) with a variable on the stack that stores the result (0 or 1) of the previous filter loop iteration (and is initialized to 1 before the loop). Thus, as soon as the filter returns 0 once, the bitmask also gets set to 0, preventing the filter from ever returning 1 again.
> 2 votes

# Answer
# Befunge, 35 Bytes

This code handles numbers between 0 and 65535

```
1&:v
v-1_@#:@#<
>\:&:2%|
 \+1p4\< ^

```

Input format :

```
number_of_values    values(separated by a space)

```

Here is a version that displays the values at the end of the process :

```
1&:v>::   v                >00g1+:4g.v
v-1_^#:>#<>$$\$1-:10p000p0-| -g01p00:<
>\:&:2%|                   @
 \+1p4\< ^

```

You may test the code here, but you will have to add a trailing line with trailing spaces, as this interpret specifies :

> « The code torus is only as large as the initial program. Insert more lines or trailing space if data will be put beyond the end of code.»

I don't know if this is acceptable, as I didn't count this trailing in the byte count
nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.

---

How does this work: The interpreter follows the arrows and skip an instruction when crossing '#'

Grey dots are test, and the red line removes unneeded variables from the stack

Using the here in the above interpreter, the saved values are displayed in the code using their representations (I don't know the format). Yes, Befunge is a quite reflective language
> 2 votes

# Answer
# 32-bit x86 machine code, 14 bytes

In hex:

```
31C9FCADD1E87203E0F941F7D9C3

```

The list of integers in machine code is something like C's "int a\[\]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.

The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.

## Disassembly:

```
31 c9     xor    ecx,ecx  ;ECX=0
fc        cld
_loop:
ad        lodsd           ;Fetch a number to EAX
d1 e8     shr    eax,1    ;EAX=>>1
72 03     jc _end         ;If CF is set then the number is odd, break
e0 f9     loopne _loop    ;--ECX; if(CF==0&&ZF==0)continue
41        inc    ecx      ;Should not include the terminating 0 into the count
_end:
f7 d9     neg    ecx      ;Counting from 0 downward, so ECX=-ECX
c3        ret

```
> 2 votes

# Answer
# Vyxal, 7 bytes

```
⁽₂Ḋ¾wJh

```

Try it Online!

### Explained

```
⁽₂Ḋ¾wJh
⁽       # 1-element lambda
 ₂      # check if even
  Ḋ     # group if true
   ¾wJ  # add empty list to end
      h # get head of the list

```
> 2 votes

# Answer
# Factor, 24 bytes

```
[ [ even? ] take-while ]

```

Attempt This Online!
> 2 votes

# Answer
# jq, 20 bytes

```
.[:map(.%2)[[1]][0]]

```

Try it online!

Explanation:

```
   map(.%2)            Maps the array items to their remainders when divided by 2
           [[1]]       Returns an array of indices where those items equal 1 (odds)
                [0]    Returns the first item of that array of indices
.[:                ]   Returns the original array up until that index

```
> 2 votes

# Answer
# tinylisp 2, 6 bytes

```
(p ] e

```

Try it at Replit. Example session:

```
tl2> (p ] e
(() remaining-args (eval (concat (q (] e)) (quote-each remaining-args))))
tl2> (def take-while-even _)
take-while-even
tl2> (take-while-even (list 2 4 6 7 8))
(2 4 6)

```

### Explanation

Uses (abbreviated aliases for) the library functions `take-while` and `even?`:

```
(p ] e)
(p    )  ; Partially apply
   ]     ; the take-while function
     e   ; to the even? function

```

---

Without using the library's `take-while` function, I found a rather elegant solution using `foldr` which is **26 bytes**:

```
(p {(\(N A)(?(e N)(c N A)(

```

That is, partially apply the `{` (foldr) function to the following argument:

```
(\(N A)(?(e N)(c N A)()))
(\                      ) ; Lambda function
  (N A)                   ; that takes a number N and a list A:
       (?              )  ;  If
         (e N)            ;  N is even
              (c N A)     ;  cons N to A
                     ()   ;  Else return empty list

```

So we end up with a function that takes a list and right-folds it on the above function, with a default starting accumulator value of nil (empty list). This starts from the right end of the list, collecting values as long as they are even, but whenever it encounters an odd value it discards all previous values and starts over.
> 2 votes

# Answer
# Rust, 25 bytes

```
|x|x.take_while(|x|x%2<1)

```
> 2 votes

# Answer
# K, 12 bytes

```
{x@&~|\2!'x}

```

## Explanation

```
{           } Function definition.
         'x   For each item in the input list...
       2!     Modulo it with 2 (e.g. 1%2, 5%2, 2%2, etc.) to get a list of booleans.
     |\       Fold | over the list to figure out where the odd numbers begin.
    ~         Flip the values it to get the beginning even numbers (until they turn odd).
   &          Get the indices.
 x@           Index the original list.

```
> 1 votes

# Answer
# Python 2, ~~59~~ ~~57~~ 56 bytes

```
def f(L,E=[]):
 while L and~L[0]%2:E+=L.pop(0),
 print E

```

**Try it online**

If printing rather than returning a list is allowed, **44 bytes**:

```
L=input()
while L and~L[0]%2:print L.pop(0)

```

And shorter by xnor, **34 bytes**, exits with an error on encountering an odd number:

```
for x in input():
    0>>x%-2;print x

```
> 1 votes

# Answer
## Minkolang 0.15, 12 bytes

```
nd2%,5&xr$N.

```

Try it here!

### Explanation

```
nd              Take number from input and duplicate
  2%            Modulo 2
    ,           Logical NOT
     5&         Pop top of stack and jump 5 spaces if truthy
       x        Dump top element
        r       Reverse stack
         $N.    Output whole stack as numbers and stop.

```

Minkolang's codebox is toroidal, so if the instruction pointer does not stop, then it loops around to the beginning again. Trying to take a number after all input has been exhausted pushes -1, which is very conveniently odd.
> 1 votes

# Answer
## Python, 43 bytes

```
lambda l:[x for x in l if l.__imul__(~x%2)]

```

Calling `l.__imul__(n)` does `l*=n`. For `n=~x%2`, it empties the list when `x` is even and otherwise leaves it unchanged. The list comprehension iterates and collect elements until it hits an odd number, which stops the iteration by emptying the list. Moreover, because it outputs the now-empty list, the `if` fails and the current odd value is not included.
> 1 votes

# Answer
# Julia 0.6, 24 bytes

```
!x=1∈x%2?!x[1:end-1]:x

```

Try it online!
> 1 votes

# Answer
## Lua, 67 Bytes

Simply iterate on each elements of the input using a `repeat..until` loop. The first iteration will use `i=0`, which isn't the first element of the input as Lua's tables are 1-indexed, resulting in `r[0]=nil` which won't do anything as `r[0]` is already `nil`.

```
function f(t)r={}i=0repeat r[i]=t[i]i=i+1until t[i]%2<1return r end

```
> 1 votes

# Answer
# C, ~~73~~ ~~69~~ ~~63~~ ~~60~~ ~~54~~ ~~45~~ 42

This requires a NULL-terminated array of strings as input. It modifies the parameter by chopping the list down to only even entries.

```
f(char**v){for(;*v&&~atoi(*v++)&1;);*v=0;}

```

If printing is allowed (45 bytes, doesn't modify parameter):

```
f(char**v){for(;*v&&~atoi(*v)&1;puts(*v++));}

```

Here is the previous complete program version (63 bytes):

```
i;main(int c,char**v){for(;(++i<c)-(atoi(v[i])&1);puts(v[i]));}

```

Takes input as program arguments.
> 1 votes

# Answer
# Perl, 21 bytes

20 bytes code + 1 bytes command line (-p)

```
s/ ?\d*[13579]\b.*//

```

Usage example:

```
echo "20 4 6 5 3 4" | perl -pe "s/ ?\d*[13579]\b.*//"

```
> 1 votes

# Answer
# PowerShell 26 bytes

```
process{if($_%2){break}$_}

```

Explanation

```
process{if($_%2){break}$_}
process{                 } # runs the script block once per item in the passed parameter
        if($_%2){break}    # if odd, break out of process{}
                       $_  # implicit output

```

Testing (save as evenodd.ps1):

```
PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372

```
> 1 votes

# Answer
# Common Lisp, 44 bytes

```
 (loop as x in(read)while(evenp x)collect x)

```

Try it online!
> 1 votes

# Answer
# Husk, 3 bytes

```
↑¦2

```

Try it online!

After my adventures with using drop-while to set a default input value with Husk's type inference system, I jumped at the opportunity to use take-while for something normal.

```
↑      The largest prefix of
       the input
 ¦     in which each element is divisible by
  2    two.

```
> 1 votes

# Answer
# Java (JDK), 58 bytes

```
a->a.stream().mapToInt(i->i).takeWhile(i->i%2<1).toArray()

```

Try it online!

Takes a `List<Integer>` and outputs an `int[]`.
> 1 votes

# Answer
# Ruby, 25 bytes

```
->a{a.take_while &:even?}

```

Attempt This Online!
> 1 votes

# Answer
# J-uby, 18 bytes

```
:take_while+:even?

```

Attempt This Online!
> 1 votes

# Answer
# ARM Thumb-2 machine code, 12 bytes

```
00000000: 04 c8 52 ea c2 72 04 c1 fa d5 70 47              ..R..r....pG

```

Assembly:

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl takewhile
    .thumb_func
    // input: int *, r0
    // output: int *, r1
    // lists are terminated with a negative number
takewhile:
.Lloop:
    // Load number into r2, increment r0
    ldmia   r0!, {r2}
    //  1. shift the LSB of r0 into the MSB
    //  2. Logical OR
    //  3. Set flags on the result
    // On either a terminator or an odd number, the MSB
    // will be set, which sets the N flag. Additionally,
    // this will terminate the list when stored.
    //    r2 = r2 | (r2 << 31);
    //    NF = r2 & 0x80000000;
    orrs.w  r2, r2, r2, lsl #31
    // Store r2 into r1, increment r1
    stmia   r1!, {r2}
    // Loop if MSB was not set (N flag not set)
    bpl     .Lloop
    // Return
    bx      lr

```

This function requires and outputs an array of positive `int32_t`s terminated with any negative `int32_t`. It follows standard C calling convention:

```
#include <stdint.h>
#include <stdio.h>
void takewhile(const int32_t *input /* r0 */, int32_t *output /* r1 */);

int main(void)
{
    const int32_t input[5] = { 171480372, 13, 14, 42, -1 };
    int32_t output[5];
    takewhile(input, output);
    for (int i = 0; output[i] >= 0; i++) {
        printf("%d, ", output[i]);
    }
    putchar('\n');
}

```

This takes advantage of the "numbers are positive" condition, and how ARM lets me set the condition codes for free.

I repeatedly logical OR the lowest bit of the values with the highest bit, and test the result. If the result is negative, one of the following is true:

1. The end of the list was reached (the upper bit was already set)
2. The number was odd (the lowest bit was set, which when shifted sets the upper bit).

With the example above, the outputted values will be this:

```
{ 171480372, /* -2147483635 */ 13 | 0x80000000 }

```
> 1 votes

# Answer
# Go, ~~78~~ 64 bytes

```
func(s[]int,c func(int)){for _,x:=range s{if x%2>0{break}
c(x)}}

```

Attempt This Online!

* -14 bytes by @Steffan

### Go, generic with predicate, 96 bytes

```
func f[T any](s[]T,b func(T)bool)(o[]T){for i:=0;i<len(s)&&b(s[i]);i++{o=append(o,s[i])}
return}

```

Attempt This Online!
> 1 votes

# Answer
# Prolog (SWI), 59 bytes

```
[]+[].
[H|_]+[]:-1is H mod 2.
[H|T]+[H|R]:-0is H mod 2,T+R.

```

Try it online!
> 1 votes

# Answer
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
t@E

```

Try it online!

Builtin. Can't have a functional language without one.

```
t@E
t@  # Take while
  E # Even

```
> 1 votes

# Answer
# Nim, 87 bytes

```
proc t(a:seq[int]):seq[int]=
  var i=0;while i<a.len and a[i]mod 2==0:inc i
  a[0..i-1]

```

Attempt This Online!
> 1 votes

# Answer
# Thunno `X`, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
lX{D2%)xsTX

```

#### Explanation

```
lX{D2%)xsTX  # Implicit input
lX           # Store [] in x
  {          # Loop through the input list:
   D         #   Duplicate
    2%)      #   If it's odd, break
       xsT   #   Otherwise, append to x
          X  #   And store the result in x
             # The X flag pushes x at the end
             # Implicit output

```

#### Screenshot
> 1 votes

# Answer
# PARI/GP, 23 bytes

```
a->i=0;[t|t<-a,!i+=t%2]

```

Attempt This Online!
> 1 votes

# Answer
# Japt `-g`, ~~3~~ 2 bytes

```
ôu

```

Try it here
> 1 votes

# Answer
# Ly, 16 bytes

```
&nr[:2%[;]pu9`o]

```

Try it online!

Pretty brute force, but it's relatively short too. :)

```
&nr              - Read in list of numbers, reverse stack
   [           ] - Loop until the stack is empty
    :2%          - Dup next number, compute 1|0 if odd/even
       [;]       - If odd, exit the program
          p      - Delete if/then boolean
           u     - Print the number, since it's even
            9`o  - Push 10 (LF) and print as character

```
> 1 votes

# Answer
# ReRegex, 24 bytes

```
,?\d*[13579]\b.*//#input

```

Try it online!

Takes input as a line of comma deliminated Integers. Matches any odd number, and replaces it and the rest of the line with nothing.
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
(ɗS;ṫ

```

Attempt This Online!

#### Explanation

```
(ɗS;ṫ  # Implicit input
(  ;   # while loop
 ɗS    # (condition) at least one odd number in the list
    ṫ  # (body) remove the last item
       # Implicit output

```
> 1 votes

# Answer
# Nekomata, 5 bytes

```
Ö∫¬∑T

```

Attempt This Online!

```
Ö∫¬∑T
Ö       Modulo 2
 ∫      Cumulative sum
  ¬     Logical NOT
   ∑    Sum
    T   Take; get the prefix with the given length

```

---

# Nekomata, 5 bytes

```
pᵖ½al

```

Attempt This Online!

```
pᵖ½al
p       Non-deterministically choose a prefix
 ᵖ½     Check that all elements are even
   al   Get the last possible value

```
> 1 votes

# Answer
# Uiua, 7 bytes

```
▽\×¬◿2.

```

Try it!

```
▽\×¬◿2.
      .  # duplicate
    ◿2   # modulo two
   ¬     # not
 \×      # scan by multiplication
▽        # keep input elements indicated by mask

```
> 1 votes

# Answer
# K (ngn/k), 7 bytes

```
(|\2!)_

```

Try it online!

* `(...)_` set up a weed-out; drop elements from the (implicit) right argument where the code in `(...)` returns a positive integer (for each item of the input)
* `|\2!` do a max-scan on the input mod'ed by 2
> 1 votes

# Answer
# Python, 55

```
t=lambda A,i=0:i<len(A)and~A[i]%2and[A[i]]+t(A,i+1)or[]

```

The following one is a generator, so it doesn't return a `list`, **49** bytes:

```
def t(A):
 for a in A:
  if a%2:break
  else:yield a

# usage: list(t([2, 3, 4]))

```
> 0 votes

# Answer
# Perl, 29 + 1 (for `-p`) = 30 bytes

```
s/(\d+)/($1)[$o or$o=$1%2]/eg

```

Use like `perl -p myfile.pl`, where `myfile.pl` contains the above code, or just `perl -pn 's/(\d+)/($1)[$o or$o=$1%2]/eg'`. Takes input from standard input.
> 0 votes

# Answer
# JavaScript, 29 bytes

`a=>a.filter(e=>!(s|=e%2),s=0)`

**or**

`a=>a.filter(e=>s&=!(e%2),s=1)`

### How it works (1st version)

1) Take input array `a` and return the result of calling `filter` on it. This will keep every element for which the function we pass into `filter` returns a truthy value.

2) Abuse the second parameter to `filter` (normally used to set the `this` value to the function, but we don't use `this` in the program) to initialize `s` to 0.

3) For the filter function, set `s` to `s | (e % 2)`, which will evaluate `s` to 0 iff `s` was 0 before and the element `e` is even. So, `s` will be 0 up until the first odd value, after which it will never be 0 again. Then simply return the negation of s, keeping the first run of even values (`!0 === true`) and discarding the rest.
> 0 votes

# Answer
# TSQL 67 bytes

```
DECLARE @ table(i INT identity, n INT)
INSERT @ values(14),(42),(2324),(97090),(4080622),(1),(171480372)

SELECT n FROM(SELECT n,sum(n%2)over(order by i)z FROM @)x WHERE z=0

```

Fiddle
> 0 votes

# Answer
# Factor, 55 bytes

```
[ dup [ odd? ] find drop over length over swap ? head ]

```

Using the following substitution regexes, the test cases from the question can be turned into a Factor test suite.

```
s/\[((?:\d*(?: )?)*)\]\s+->\s+\[((?:\d*(?: )?)*)\]/{ { $2 } } [ { $1 } take-while-even ] unit-test/g
s/,//g

```

**takewhile-even.factor**

```
USING: kernel math sequences ;
IN: takewhile-even

: take-while-even ( seq -- newseq )
  dup [ odd? ] find drop over length over swap ? head ;

```

**takewhile-even-tests.factor**

```
USING: tools.test takewhile-even ;
IN: takewhile-even.tests

{ { 14 42 2324 97090 4080622 171480372 } } [ { 14 42 2324 97090 4080622 171480372 } take-while-even ] unit-test
{ { 42 14 42 2324 } } [ { 42 14 42 2324 } take-while-even ] unit-test
{ {  } } [ { 7 14 42 } take-while-even ] unit-test
{ {  } } [ {  } take-while-even ] unit-test
{ { 171480372 } } [ { 171480372 13 14 42 } take-while-even ] unit-test
{ { 42 14 42 } } [ { 42 14 42 43 41 4080622 171480372 } take-while-even ] unit-test

```

Run them with `"takewhile-even" test`.
> 0 votes

# Answer
## Perl 5.10, 36 bytes

Different way of doing it when compared to the other Perl answers which are based on regexes. 35 bytes + 1 byte for ***-a*** flag.

```
for(@F){$_%2?last:push@a,$_}say"@a"

```

Try it here!
> 0 votes

# Answer
# Java, 98 bytes

```
int[]f(int[]t){int i=0;for(;i<t.length&&t[i]%2<1;i++);return java.util.Arrays.copyOfRange(t,0,i);}

```

Ideone it!
> 0 votes

# Answer
# PHP, ~~57~~ 55 bytes

```
function f($i){foreach($i as $n){if($n&1)die;echo $n;}}

```

Ungolfed:

```
function f($i){
    foreach($i as $n){
        if($n & 1) die;
        echo $n;
    }
}

```

The function takes an array `$i` as an input parameter.

`$n & 1` will return 1 if `$n` is odd and 0 is `$n` is even.
> 0 votes

# Answer
# Python 3, 72 bytes

It's a bit of a boring answer, but itertools has a function for this...

```
from itertools import*
lambda x:[i for i in takewhile(lambda y:y%2+1,x)]

```

An anonymous function that takes input of the list `x` via argument and returns a list.

Try it on Ideone
> 0 votes

# Answer
# \>\<\>, 70 bytes

Takes input as any number of decimal integers separated by a single character (anything but a digit), and prints out the list newline-separated.

```
v;oan;?<
0!2&::&\%
&>i:0(?^'0'-::0($9)+?v&a*+&!
>^   oan&0~&;?%2&::&~<

```

Try it online!
> 0 votes

# Answer
# Javascript (using external library - Enumerable) (42 bytes)

```
n=>_.From(n).TakeWhile(y=>y%2<1).ToArray()

```

Code explanation: Library built in implementation...
> 0 votes

# Answer
# Tcl, 44 bytes

```
proc T L {lmap e $L {if $e%2 {break}
set e}}

```

Try it online!

~~Tcl, 64 bytes
```
proc T L {set M {}
lmap e $L {if $e%2 break
lappend M $e}
set M}

```
Try it online!<br>~~
> 0 votes

# Answer
# Funky, 44 bytes

```
t=>{z={}fori=0;(!t[i]&1)*i<#t;i++z[i]=t[i]z}

```

Try it online!
> 0 votes

# Answer
# GNU sed, 20 bytes

```
s/[^ ]*[13579]\b.*//

```

Try it online!

Input and output are space-separated numbers.

## Alternate solution, 22 bytes (20 + `-n`)

```
s/[24680]$/&/p;t;q;:

```

Try it online! Uses newlines instead of spaces this time.
> 0 votes

# Answer
# tinylisp repl, 61 bytes

```
(load library)(d E(q((L)(i(i L(even?(h L))L)(c(h L)(E(t L)))(

```

Defines a function `E` (short for "take while Even"). Try it online!

### Ungolfed

```
(load library)
(def takewhile-even
 (lambda (ls)
  (if
   (if ls (even? (head ls)) ls)
   (cons (head ls) (takewhile-even (tail ls)))
   nil))))

```

Recurse through the list, using `cons` to build the result list. If the list is empty or if `even?` returns false, return empty list.

**Note #1:** Your functional programming professor would not like this function. It's not tail-recursive, so it will hit the recursion limit for long lists. Tail-recursive version is 73 bytes:

```
(load library)(d E(q((L A)(i(i L(even?(h L))L)(E(t L)(c(h L)A))(reverse A

```

or ungolfed:

```
(load library)
(def takewhile-even
 (lambda (ls accum)
  (if
   (if ls (even? (head ls)) ls)
   (takewhile-even
    (tail ls)
    (cons (head ls) accum))
   (reverse accum))))

```

**Note #2:** The specification of "take while *even*" actually costs bytes in tinylisp: `even?` isn't built-in, so we have to load the library (which is expensive) or reimplement the function (which is worse). Generic `takewhile` with the predicate as a second argument is only **46 bytes**:

```
(d T(q((L P)(i(i L(P(h L))L)(c(h L)(T(t L)P))(

```

or ungolfed:

```
(load library)
(def takewhile
 (lambda (ls predicate)
  (if
   (if ls (predicate (head ls)) ls)
   (takewhile (tail ls) predicate)
   nil)))

```

(I think I may have my next standard library function here...)
> 0 votes

# Answer
# Java 8, ~~79~~ 71 bytes

```
l->{int i=0;for(int n:l){if(n%2>0)return l.subList(0,i);i++;}return l;}

```

**Explanation:**

Try it here.

```
l->{             // Method with ArrayList<Integer> as parameter and List as return-type
  int i=0;       //  Index-integer
  for(int n:l){  //  Loop over the input-List
    if(n%2>0)    //   If the current item is odd:
      return l.subList(0,i);
                 //    Return a sub-List from 0 through index `i` (exclusive)
    i++;         //   At the end of every iteration: increase index `i` by 1
  }              //  End of loop
  return l;      //  If the input-List was empty or contained no odd values, return itself
}                // End of method

```
> 0 votes

# Answer
# Perl 5, 18 + 1 (for `a`) = 19 bytes

Uses `-aE` instead of `-ae`.

```
$_%2?die:say for@F

```
> 0 votes

# Answer
# Stax, 9 bytes

```
{O{|e*cf}

```

This is a block (equivalent to a function) that takes a list and returns a list on the top of the stack. The link below attaches some footers to output the list.

Run and debug online!

## Explanation

```
{O{|e*cf}
{       }    Define a block
 O           Put 1 under top of stack, used as an accumulator
  {    f     Filter array with accumulator
   |e        True if array element is even, false if odd
     *c      `And` with accumulator

```
> 0 votes

# Answer
# Add++, 14 bytes

```
L*,bU1€+2↑%1€_

```

Try it online!

## How it works

```
L*,		; Declare 'lambda 1' that returns the stack
		; Example argument:		[[12 14 16 17 18 20]]
	bU	; Unpack;		STACK = [12 14 16 17 18 20]
	1€+	; Increment each;	STACK = [13 15 17 18 19 21]
	2↑%	; Takewhile odd;	STACK = [13 15 17]
	1€_	; Decrement each;	STACK = [12 14 16]

```
> 0 votes

# Answer
## Javascript (ES2015) , 42 Bytes

I wasn't sure if the expected implementation was of the actual higher order function or the special case of getting a list of all even numbers, so i did both. Byte count is for longest of the two (higher order)

Even numbers (39 bytes)

```
l=>(o=[],l.every(v=>~v%2&&o.push(v)),o)

```

Higher order function:

```
f=>l=>(o=[],l.every(v=>f(v)&&o.push(v)),o)

```

higher order function called using curry style syntax

```
f(predicate)(list) => list

```
> 0 votes

# Answer
# Arturo, ~~45~~ ~~36~~ 20 bytes

```
$=>[collect&=>even?]

```

Try it
> 0 votes

# Answer
# Julia 0.6, 22 bytes

```
!x=x[cumprod(@.x%2<1)]

```

Try it online!

also works in julia 1.x

there is `Iterators.takewhile` but it is way too long
> 0 votes

# Answer
# C (GCC), 43 bytes

```
i;f(a,n)int*a;{for(;i<n&&~a[i]%2;i++);a=i;}

```

Attempt This Online!

I/O format: Takes a list and its length, returns the length to which the input list needs chopped. Tricks: `~a[i]%2` checks if `a[i]` is even, `a=i;` loads `i` to `rax` with `-O0`, hence avoiding a `return`. Also uses K&R function declaration and implicit int.
> 0 votes

# Answer
# Perl 5 `-p`, 9+1 = 10 bytes

(Scored under the system in place at the time of the question.)

```
$_%2&&die

```

Try it online!

Input and output both have the entries line separated.
> 0 votes

---
Tags: code-golf, array, functional-programming
---