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:
takeWhile (predicate) list
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 be Number
and String
.(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.
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])
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]
.(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 []
.(\x -> 2*x < 10)
is a user-defined function which selects elements in the list that are less than 10 when multiplied by 2.main :: IO ()-- Select the first wordmain = print(takeWhile (/= ' ') "edpresso shot") >>-- Select elements in the list which are greater than '!'print(takeWhile ('!'<) "hello! world")
(/= ' ')
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.('!'<)
returns string elements that have an !
. Since ' '
has an ASCII value less than '!'
, the loop exits and returns "hello"
.dropWhile
is a related function.