Is there a way to tell if a list in Haskell is infinite? The reason is that I don\'t want to apply functions such as length
to infinite lists.
The Halting Problem was first proved unsolvable by assuming a Halting Oracle existed, then writing a function that did the opposite of what that oracle said would happen. Let's reproduce that here:
isInfinite :: [a] -> Bool
isInfinite ls = {- Magic! -}
Now, we want to make a list impossibleList
that does the opposite of what isInfinite
says it should. So, if impossibleList
is infinite, it is actually []
, and if it isn't infinite, it is something : impossibleList
.
-- using a string here so you can watch it explode in ghci
impossibleList :: [String]
impossibleList =
case isInfinite impossibleList of
True -> []
False -> "loop!" : impossibleList
Try this out yourself in ghci with isInfinite = const True
and isInfinite = const False
.