eyes enberg
eyes enberg

Reputation: 586

A little confusion with the sorted function in Haskell

sorted :: Ord a => [a] -> Bool
sorted xs = and [x <= y | (x,y) <- pairs xs]

Can anyone explain to me what this random and is doing after =? It works when I compile it but it doesn't make logical sense to me. Is it because Haskell works recursively and it uses the and to compare the next item?

Any insight is highly appreciated.

Upvotes: 1

Views: 127

Answers (2)

Ben
Ben

Reputation: 71400

and is not the function for taking the logical-and of two boolean values; that's && (with type Bool -> Bool -> Bool).

Instead and has type [Bool] -> Bool; it condenses an arbitrary number of boolean values down to a single one by "anding them all".

Upvotes: 1

David Young
David Young

Reputation: 10783

If a function pairs :: [a] -> [(a, a)] is defined somewhere, the expression

[x <= y | (x,y) <- pairs xs]

is a list of a booleans (that is, its type is [Bool]). and is a function whose type is [Bool] -> Bool: It takes a list of booleans and it gives back True if all of the booleans in the list are True and False otherwise.

and [x <= y | (x,y) <- pairs xs] is a function application (and is being applied to the value created by the list comprehension).

One thing to note is that Haskell doesn't have a lot of special keywords, comparatively. Many operations are represented by functions rather than by special syntax or keywords.

Upvotes: 8

Related Questions