例如,我正在为列表编写一些函数,我想使用长度函数
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 == 100How 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) == 100instead 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. 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) xsYou can use the same idea to write the lengthIsAtLeast and lengthIsAtMost variants.
更多推荐
有没有办法将无限和有限的列表分开?
发布评论