Kimberly
Kimberly

Reputation: 17

haskell function gap that takes in list of elements and returns true if gap

I am trying to create a haskell function that takes in a list of elements and returns true if there is a space and false if there is not.

Here is what I have, when running the test it returns all true. When the first 2 cases shuld be false.

gaps :: (Enum t, Eq t) => [t] -> Bool
gaps [] = False
gaps [x] = False
gaps (x:y:xs) = if y == (succ x) then gaps (y:xs) else True

gapsTests = [
          not $ gaps [1..10]
         ,not $ gaps "ABCD"
         ,gaps "ABD"
         ,gaps [1,2,3,5,6]
         ,gaps "ABBC"
        ]

Upvotes: 1

Views: 203

Answers (3)

amalloy
amalloy

Reputation: 92077

You could avoid doing the recursion and case analysis yourself by just comparing to the list you expect to find, [x..y]:

gaps :: (Enum t, Eq t) => [t] -> Bool
gaps [] = False
gaps xs@(x:_) = not (and (zipWith (==) xs [x..]))

Upvotes: 1

Will Ness
Will Ness

Reputation: 71109

if A then B else True is the same as if not A then True else B which is the same as not A || B.

You can thus rewrite your code as

gaps :: (Enum t, Eq t) => [t] -> Bool
gaps (x:y:xs)  =  (y /= succ x) || gaps (y:xs)
gaps _  =  False

Then,

> gaps [1..10]
False                         -- no gaps

> gaps "ABC"
False                         -- no gaps

> gaps ("ABD" ++ undefined)
True                          -- there's a gap here

The input is only visited for as many elements as needed to get a result. his is known as "lazy evaluation".

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

The first two cases return True as well, since we use a not $ in front. We thus check if there are no gaps for [1..10] and no gaps for "ABCD", that holds in both cases:

gapsTests = [
    not $ gaps [1..10]   -- check if the list does not contain any gaps
  , not $ gaps "ABCD"    -- check if the list does not contain any gaps
  , gaps "ABD"           -- check if the list does contain any gaps
  , gaps [1,2,3,5,6]     -- check if the list does contain any gaps
  , gaps "ABBC"          -- check if the list does contain any gaps
  ]

This thus means that all items of your gapsTests should be True. If that is the case, the tests are successful.

Upvotes: 1

Related Questions