What is takeWhile in Haskell?

Overview

takeWhile is a built-in method in Haskell that inspects the original list using a given predicate and returns its elements until the condition is false.

The flow diagram for the takeWhile loop is shown below in Figure 1. A list and a predicate p are given:

Figure 1

Syntax

takeWhile (predicate) list

Parameters

The takeWhile method takes the following parameters:

  1. predicate: This is the condition applied on each list item. It can be a simple comparison operator (such as (x > 6)) or a user-defined function such as (\x -> 2*x < 10).
  2. list: The list type may be Number and String.

Return type

(a -> Bool) -> [a] -> [a]

When applied to a list x using a predicate p, the takeWhile method returns the longest prefix of x containing elements that satisfy p. The resulting list may or may not be empty.

Code example 1: Integer comparisons

main :: IO ()
-- Select elements in the list that are less than 6
main = print(takeWhile (< 6) [0,2,4,6,8,10]) >>
-- Select elements in the list that are odd
print(takeWhile (odd) [0,2,4,6,8,10]) >>
-- Select elements in the list that, when multiplied by 2,
-- are less than 10
print(takeWhile (\x -> 2*x < 10) [0,2,4,6,8,10])

Code explanation

  • Line 3: The takeWhile function compares each element in the given list [0,2,4,6,8,10] to the predicate (<6). If the element is less than 6, it is returned. Therefore, the final list will be [0,2,4].
  • Line 6: The given predicate (odd) is a built-in method in Haskell that returns True if the element is odd. Since the given list [0,2,4,6,8,10] has no odd elements, the takeWhile function returns an empty list [].
  • Line 10: The predicate (\x -> 2*x < 10) is a user-defined function which selects elements in the list that are less than 10 when multiplied by 2.

Code example 2: String comparisons

main :: IO ()
-- Select the first word
main = print(takeWhile (/= ' ') "edpresso shot") >>
-- Select elements in the list which are greater than '!'
print(takeWhile ('!'<) "hello! world")

Code Explanation

  • Line 3: The predicate (/= ' ') checks each string character and returns when the first space is encountered. In this case, the takeWhile function returns "edpresso", which is the first word of the string.
  • Line 6: The predicate ('!'<) returns string elements that have an ASCII valueThe American Standard Code for Information Interchange, or ASCII, is a character encoding standard for text files in electronic communication. greater than the ASCII value of !. Since ' ' has an ASCII value less than '!', the loop exits and returns "hello".

Related functions

dropWhile is a related function.