How to tell if a list is infinite?

后端 未结 6 428
迷失自我
迷失自我 2020-12-15 03:07

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.

6条回答
  •  囚心锁ツ
    2020-12-15 03:53

    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.

提交回复
热议问题