7 kyu

The dropWhile Function

1,790 of 3,470jgdodson

Description:

Yet another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to remove the longest prefix of elements such that the predicate is true for each element. We'll call this the dropWhile function. It accepts two arguments. The first is the sequence of values, and the second is the predicate function. The function does not change the value of the original sequence.

def isEven(num):
  return num % 2 == 0

arr = [2,4,6,8,1,2,5,4,3,2]

dropWhile(arr, isEven) == [1,2,5,4,3,2] # True
function isEven(num) {
  return num % 2 === 0;
}
var seq = [2,4,6,8,1,2,5,4,3,2];

dropWhile(seq, isEven) // -> [1,2,5,4,3,2]
dropWhile [2,4,6,8,1,2,5,4,3,2] even -- -> [1,2,5,4,3,2]
auto isEven = [](int value) -> bool { return abs(value) % 2 == 0; };

dropWhile({ 2, 4, 6, 8, 1, 2, 5, 4, 3, 2 }, isEven) // -> { 1, 2, 5, 4, 3, 2 }
Func<int, bool> isEven = (value) => value % 2 == 0;

dropWhile(new int[] { 2, 4, 6, 8, 1, 2, 5, 4, 3, 2 }, isEven) // -> { 1, 2, 5, 4, 3, 2 }
drop-while [2,4,6,8,1,2,5,4,3,2] even  -->  [1,2,5,4,3,2]
local function is_even(x)
  return x%2==0
end

drop_while({2,4,6,8,1,2,5,4,3,2}, is_even)  -->  [1,2,5,4,3,2]
let is_even n = n mod 2 = 0 in
drop_while [2; 4; 6; 8; 1; 2; 5; 4; 3; 2] is_even
  (* -> [1; 2; 5; 4; 3; 2] *)
bool isEven (int n) { return (n % 2) == 0; }
size_t count;
int *result = dropWhile((int[]) {2, 4, 5, 7, 8, 10 }, 6, isEven, &count);
// result = { 5, 7, 8, 10 }; count = 4

Your task is to implement the dropWhile function. If you've got a span function lying around, this is a one-liner! Alternatively, if you have a takeWhile function on your hands, then combined with the dropWhile function, you can implement the span function in one line. This is the beauty of functional programming: there are a whole host of useful functions, many of which can be implemented in terms of each other.

Functional Programming
Arrays
Algorithms

Stats:

CreatedMar 6, 2015
PublishedMar 6, 2015
Warriors Trained8179
Total Skips363
Total Code Submissions11626
Total Times Completed3470
JavaScript Completions1790
Haskell Completions231
CoffeeScript Completions19
C++ Completions271
C# Completions237
Python Completions880
C Completions115
Ruby Completions100
λ Calculus Completions17
OCaml Completions41
Factor Completions11
Lua Completions26
Total Stars86
% of votes with a positive feedback rating89% of 514
Total "Very Satisfied" Votes417
Total "Somewhat Satisfied" Votes77
Total "Not Satisfied" Votes20
Ad
Contributors
  • jgdodson Avatar
  • jhoffner Avatar
  • JoshSchreuder Avatar
  • bkaes Avatar
  • Unnamed Avatar
  • GiacomoSorbi Avatar
  • Dentzil Avatar
  • JohanWiltink Avatar
  • lilsweetcaligula Avatar
  • Voile Avatar
  • monadius Avatar
  • hobovsky Avatar
  • trashy_incel Avatar
  • akar-0 Avatar
  • Kacarott Avatar
  • tri@ Avatar
  • dfhwze Avatar
  • Glinator Avatar
  • fcr-- Avatar
Ad