Search code examples
haskellfunctional-programming

Checking to see if a list is ordered consecutively


Is there any library function in Haskell that'll allow me to check if a list is ordered consecutively? eg. [1,2,3,4] is valid, [1,2,3,10] is invalid.

Basically I can have a list that ranges anywhere between 3 to 5 elements and I'm trying to check if that list is ordered consecutively.

My Attempt (I'm not sure if this is the right way to approach it, seems to be way too much repetition)

isSucc:: [Integer] -> Bool
isSucc[]            = True
isSucc(x:y:zs)      = 
    if (x+1) == y
    then True && isSucc(y:zs)
    else isSucc(y:zs)

After I have this function working, I'm planning on using it to filter a lists of lists (Keep the list inside the list only and only if it is ordered consecutively)


Solution

  • There's no standard function for that.

    Here's a fixed version of your function, making it generic, removing the redundant conditions and adding the missing ones:

    isSucc :: (Enum a, Eq a) => [a] -> Bool
    isSucc [] = True
    isSucc (x:[]) = True
    isSucc (x:y:zs) | y == succ x = isSucc $ y:zs
    isSucc _ = False