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

• Is it OK if I return an iterator, rather than a list? – DJMcMayhem Jul 5 '16 at 19:45
• @DrGreenEggsandIronMan I'm guessing your function has to be able to take its output as its input, guaranteeing they are in the same format. – mbomb007 Jul 5 '16 at 19:47
• @DrGreenEggsandIronMan, I don't think that returning a sublist should be exploited here in the output format. (It's still up to you if you exploit this in your code though). Mbomb's criterion looks most appropriate and compatible with the current challenge so it will be "your output should be a valid input at the very least". – SEJPM Jul 5 '16 at 20:00

## Mathematica, 18 bytes

#~TakeWhile~EvenQ&


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

• How many built-ins does Mathematica have? Seems as if it has one for almost anything. – Emigna Jul 5 '16 at 19:06
• @Emigna I haven't counted, but Rule #110 of the internet is, "If it exists, there's a Mathematica built-in for it." – Martin Ender Jul 5 '16 at 19:07
• @MartinEnder Too bad that Rule #110.5 of the internet is, "If it involves strings in any way whatsoever, then it is not considered to exist for the purposes of Rule #110." – LegionMammal978 Jul 6 '16 at 11:26
• @LegionMammal978 The workaround is to make strings heads of expressions :) – LLlAMnYP Jul 7 '16 at 11:03

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.

# 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

• Is this normal, that the code says "toys" with a smile there? – SEJPM Jul 5 '16 at 18:56
• @SEJPM to~Y<) also works, but I like this one better :-) – Luis Mendo Jul 5 '16 at 18:56

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

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

## C#, 50 bytes

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

• You can use a lambda directly. It is valid as far as I know. a=>a.TakeWhile(x=>x%2<1); – aloisdg moving to codidact.com Jul 6 '16 at 17:02

# 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


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


• You can take the list in binary? – Leaky Nun Jul 7 '16 at 10:37

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

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


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

# Dyalog APL, 11 bytes

{⍵/⍨∧\~2|⍵}


2| division remainder from dividing with 2

~ negate

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

/⍨ select where

# Ruby, 25 bytes

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


I think I lose...

• Can you do ->a{a.take_while &:even?} or at least ->a{a.take_while(&:even?)}? – Martin Ender Jul 5 '16 at 19:11
• @MartinEnder Thank you. I was looking for something like that, but I guess I am not well versed in ruby golfing syntax. – MegaTom Jul 5 '16 at 19:13

## Pyke, 8 bytes

0+2L%fhO


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]


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


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

# 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

: 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

• After finishing this, I realized my breakfast was cold. :( – mbomb007 Jul 6 '16 at 14:54
• Too often I find my dinner cold after golfing code at the table. Perhaps Factor will let you be more productive and golfier at the same time? :D – cat Jul 6 '16 at 20:03
• @c I do my code development for PPCG with online IDEs. But I use Forth because I already know it, it's just difficult to manage a stack in my head. I originally learned Forth because a Minecraft mod added redstone computers that ran a version of Forth entitled MineOS. – mbomb007 Jul 6 '16 at 20:13

# 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