简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM