Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 someone understand could this function be used with infinite lists or not?

Or should I always think about infinite lists and use something like this

foo :: [a] -> Bool
foo xs = length (take 101 xs) == 100

instead of using length directly?

What if haskell would have FiniteList type, so length and foo would be

length :: FiniteList a -> Int
foo :: FiniteList a -> Bool
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
997 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...