问题描述
例如,我正在为列表编写一些函数,我想使用长度函数
foo :: [a] - > Bool
foo xs = length xs == 100
或者我应该总是考虑无限列表并使用类似这样的内容
foo :: [a] - > Bool
foo xs =长度(取101 xs)== 100
代替长度直接吗?
如果haskell具有FiniteList类型,那么length和foo将会是
length :: FiniteList a - > Int
foo :: FiniteList a - > Bool
length
遍历整个列表,但要确定列表是否具有特定长度 n
,则只需查看第一个 n
元素。
使用取
的想法可行。或者
,你可以这样写一个 lengthIs
函数:
- 假设n> = 0
lengthIs 0 [] = True
lengthIs 0 _ = False
lengthIs n [] = False
lengthIs n(x:xs)= lengthIs(n-1)xs
您可以使用相同的思路编写 lengthIsAtLeast
和 lengthIsAtMost
变体。
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
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. Alternativelyyou 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.
这篇关于有没有办法将无限和有限的列表分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!