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:
Syntax
takeWhile (predicate) list
Parameters
The takeWhile method takes the following parameters:
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).list: The list type may beNumberandString.
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 6main = print(takeWhile (< 6) [0,2,4,6,8,10]) >>-- Select elements in the list that are oddprint(takeWhile (odd) [0,2,4,6,8,10]) >>-- Select elements in the list that, when multiplied by 2,-- are less than 10print(takeWhile (\x -> 2*x < 10) [0,2,4,6,8,10])
Code explanation
- Line 3: The
takeWhilefunction 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 returnsTrueif the element is odd. Since the given list[0,2,4,6,8,10]has no odd elements, thetakeWhilefunction 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 wordmain = 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, thetakeWhilefunction returns"edpresso", which is the first word of the string. - Line 6: The predicate
('!'<)returns string elements that have an greater than the ASCII value ofASCII value The American Standard Code for Information Interchange, or ASCII, is a character encoding standard for text files in electronic communication. !. Since' 'has an ASCII value less than'!', the loop exits and returns"hello".
Related functions
dropWhile is a related function.