Is there any way to separate infinite and finite lists?

后端 未结 5 1621
猫巷女王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:34

    length traverses the entire list, but to determine if a list has a particular length n you only need to look at the first n elements.

    Your idea of using take will work. Alternatively you can write a lengthIs function like this:

    -- assume n >= 0
    lengthIs 0 [] = True
    lengthIs 0 _  = False
    lengthIs n [] = False
    lengthIs n (x:xs) = lengthIs (n-1) xs
    

    You can use the same idea to write the lengthIsAtLeast and lengthIsAtMost variants.

提交回复
热议问题