6 kyu

The takeWhile Function

1,365 of 2,459jgdodson

Description:

Here's another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to get the longest prefix of elements such that the predicate is true for each element. We'll call this the takeWhile 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.

Example:

sequence : [2,4,6,8,1,2,5,4,3,2]
predicate: is an even number
result   : [2,4,6,8]

Your task is to implement the takeWhile function.

If you've got a span function lying around, this is a one-liner! Also, if you liked this problem, you'll surely love the dropWhile function.

Functional Programming
Arrays
Algorithms
Lists
Data Structures

Stats:

CreatedMar 6, 2015
PublishedMar 6, 2015
Warriors Trained4587
Total Skips225
Total Code Submissions9256
Total Times Completed2459
JavaScript Completions1365
C# Completions243
CoffeeScript Completions19
C++ Completions306
Python Completions575
λ Calculus Completions15
OCaml Completions35
C Completions53
Total Stars62
% of votes with a positive feedback rating89% of 479
Total "Very Satisfied" Votes393
Total "Somewhat Satisfied" Votes64
Total "Not Satisfied" Votes22
Total Rank Assessments96
Average Assessed Rank
6 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
8 kyu
Ad
Contributors
  • jgdodson Avatar
  • Javatlacati Avatar
  • Chrono79 Avatar
  • Dentzil Avatar
  • user5036852 Avatar
  • JohanWiltink Avatar
  • monadius Avatar
  • hobovsky Avatar
  • trashy_incel Avatar
  • Formula-9 Avatar
  • akar-0 Avatar
  • Kacarott Avatar
  • Glinator Avatar
Ad