Is there any way to separate infinite and finite lists?

后端 未结 5 1491
猫巷女王i
猫巷女王i 2020-12-16 23:25

For example, I am writing some function for lists and I want to use length function

foo :: [a] -> Bool
foo xs = length xs == 100

How can

5条回答
  •  隐瞒了意图╮
    2020-12-16 23:56

    Nats and laziness strike again:

    import Data.List
    
    data Nat = S Nat | Z deriving (Eq)
    
    instance Num Nat where
        fromInteger 0 = Z
        fromInteger n = S (fromInteger (n - 1))
    
        Z   + m = m
        S n + m = S (n + m)
    
    lazyLength :: [a] -> Nat
    lazyLength = genericLength
    
    main = do
        print $ lazyLength [1..]    == 100 -- False
        print $ lazyLength [1..100] == 100 -- True
    

提交回复
热议问题