有没有办法将无限和有限的列表分开?

编程入门 行业动态 更新时间:2024-10-28 05:13:19
本文介绍了有没有办法将无限和有限的列表分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,我正在为列表编写一些函数,我想使用长度函数

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. 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.

更多推荐

有没有办法将无限和有限的列表分开?

本文发布于:2023-10-31 01:26:05,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!