Define a function for an infinite list Haskell

Im trying to write the function
longer :: [a] -> Int -> Bool
Which decides if the provided list is longer than the parameter.
So far I wrote:

longer :: [a] -> Int -> Bool
hossz (x:xs) = length (x:xs)
hossz [] = 0
longer [] _ = False
longer (x:xs) y | y<0 = error ("negative parameter")
                    | hossz(x:xs)>y = True
                    | otherwise = False

This all works fine and dandy until I provide it with an infinite list (longer [1..] 10 for example), where it will get stuck in an infinite loop of some sort and just doesn’t finish running.
So the question is, is there maybe a way I could define it, where if it gets an infinite list it just returns True and doesn’t try to calculate the whole thing?
Thank you in advance

>Solution :

length is trying to compute the length of the list, which takes forever for an infinite list.

You don’t need to compute the length at all, though. You only need to recurse on the tail with a smaller integer. When the the integer hits 0, the list is either empty or not; it doesn’t matter how long it is.

longer :: [a] -> Int -> Bool
longer _ n | n < 0 = True
longer xs 0 = ...
longer [] n = False  -- n > 0
longer (x:xs) n = longer xs (n - 1)

Leave a Reply