Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

span function in Haskell

Tags:

list

haskell

I think that the span function is Haskell is to apply a predicate to a list, and return a tuple where the first element is elements in the list that satisfy that predicate and the second element is the reminder of the list.

And it works well when I put: span (<3) [1,2,4,5,6]. It just returns in GHCI: ([1,2], [4,5,6]).

However, when I enter span (>3) [1,2,4,5,6], it returns ([],[1,2,4,5,6]). But I thought it should return ([4,5,6],[1,2]). So I was wondering the reason of it .

like image 662
s666 Avatar asked Dec 15 '19 11:12

s666


2 Answers

Your understanding of span is not entirely correct, this is what the official docs say:

span, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list

(emphasis mine).

Hence, the predicate is applied to each element of the list starting from the beginning. This means that the predicate in

span (<3) [1,2,4,5,6]

is satisfied for the first two elements, and the result is

([1,2], [4,5,6])

But in this other example

span (>3) [1,2,4,5,6]

the first element of the list already doesn't satisfy the predicate, so the first element of the returned tuple will be an empty list.

like image 55
bugs Avatar answered Oct 28 '22 12:10

bugs


What you describe here is partition :: (a -> Bool) -> [a] -> ([a], [a]). This is a function that for a given predicate will take a list, and make a 2-tuple where the first item is a list with items that satisfy the predicate, and the second item a list of items that do not satisfy the predicate. Indeed:

Prelude Data.List> partition (>3) [1,2,4,5,6]
([4,5,6],[1,2])

span :: (a -> Bool) -> [a] -> ([a], [a]) on the other hand makes a 2-tuple where the first item is the longest prefix of elements in the list that satisfy the predicate, and the second item is the list of remaining elements. Since for span (>3) [1,2,4,5,6], the first item does not satisfy the predicate. The longest prefix is the empty list [], and all elements of the given list, appear in the second item.

like image 40
Willem Van Onsem Avatar answered Oct 28 '22 11:10

Willem Van Onsem