How do I check if a list is sorted in Haskell using list comprehension?

Viewed 312

I'm trying to check if a list is sorted either ascending or descending in Haskell. I understand list comprehension the best in Haskell right now.

Currently, I have...

ascending l = [ x > (head(tail l))| x <- l]

and

descending l = [ x < (head (tail l))| x <- l]

but it's only comparing the each item in them list against one value and returning true and false whether it's greater or less than and that's not what I'm looking for. I want it to tell me if a list is true whether it's increasing or decreasing.

1 Answers

Whether a list is sorted is a Bool, and list comprehensions always return lists, so it's impossible with nothing outside of the list comprehension, but you can do it with one function outside, like this:

ascending l = and [x <= y | (x, y) <- zip l (tail l)]
descending l = and [x >= y | (x, y) <- zip l (tail l)]

Or like this:

import Data.List
ascending l = and [x <= y | x:y:_ <- tails l]
descending l = and [x >= y | x:y:_ <- tails l]

But as n. 1.8e9-where's-my-share m. said in a comment, this really isn't the right tool for the job, so you shouldn't actually do this this way in production.

Related