Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading