user2876457
user2876457

Reputation: 47

Having Trouble with tuples in Haskell

i have this function:

pairs :: [a] -> [(a,a)]
pairs xs = zip xs (tail xs)

and i have to write another one, based on Pairs, that returns True if at least one pair of tuples is in an ascending order (e.g (2,3)).

here's my attempt at this:

unsorted :: Ord a => [a] -> Bool
unsorted xs = [if fst x < snd x then True else False| x <- pairs xs]

why is this wrong ?

Upvotes: 0

Views: 82

Answers (2)

Lee
Lee

Reputation: 144206

Your function returns a list of Bools, not a Bool. You can use any:

unsorted xs = any (\x -> fst x < snd x) xs

or

unsorted = any (\(x, y) -> x < y)

if you want to use a list comprehension you can add a filter and then see if the resulting list contains any elements:

(length [x | x <- pairs xs, fst x < snd x]) > 0

or

(length [x | (x,y) <- pairs xs, x < y]) > 0

Upvotes: 3

Stephen Diehl
Stephen Diehl

Reputation: 8439

Looking at the type error that GHC gives you should give you a hint about what the error is.

Couldn't match expected type `Bool' with actual type `[Bool]'

Your signature indicates that you want to a return a Bool but your implementation yields a list of Bools. To fix this use the function ( any :: (a -> Bool) -> [a] -> Bool ):

unsorted :: Ord a => [(a, a)] -> Bool
unsorted xs = any (\(a,b) -> a < b) xs

Upvotes: 2

Related Questions