haskell增量对的无限列表 [英] haskell infinite list of incrementing pairs

查看:170
本文介绍了haskell增量对的无限列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建包含形式(m,n),
对的无限列表对:: [(Integer,Integer)],其中m和n分别是[0 ..]的成员。另一个要求是,如果(m,n)
是列表的合法成员,那么(elem(m,n)对)应该在有限时间内返回True。
违反此要求的对的实现被认为是非解决方案。
* 新鲜编辑感谢您的评论,让我们看看我能否取得进展 *

  pairs :: [(Integer,Integer)] 
pairs = [(m,n)| t < - [0 ..],m < - [0 ..],n < - [0 ..],m + n == t]
pre>

类似这样的东西?我只是不知道它会在有限的时间内返回True。



我觉得这个问题的措辞不是我的答案的一部分。只要你打电话(elem(m,n)对)就应该返回true。声音正确吗?

解决方案

忽略助手列出所有对,但元素的顺序是一个问题。您将拥有无限多对,如(0,m),它们是后跟无限多对,如(1 ,m)。当然, elem 将永远迭代所有(0,m)对从未达到(1 ,m)(2,m)等。

我不是确定为什么你有 helper 方法 - 用它,你只是建立一个像 [(0,0),(1, 1),(2,2),...] ,因为您已经过滤 m = n 。是否是要求的一部分?



像@hammar建议的那样,从 0 = m + n 开头并列出对(m,n)。然后列出对(m,n),其中 1 = m + n 。那么你的清单看起来像 [(0,0),(0,1),(1,0),(0,2),(1,1),(2,0),。 ..]


Create an infinite list pairs :: [(Integer, Integer)] containing pairs of the form (m,n), where each of m and n is a member of [0 ..]. An additional requirement is that if (m,n) is a legit member of the list, then (elem (m,n) pairs) should return True in finite time. An implementation of pairs that violates this requirement is considered a non- solution. *Fresh edit Thank you for the comments, Lets see if I can make some progress*

    pairs :: [(Integer, Integer)]
    pairs = [(m,n) | t <- [0..], m <- [0..], n <-[0..], m+n == t]

Something like this? I just don't know where it's going to return True in finite time.

I feel the way the question is worded elem doesn't have to be part of my answer. Just if you call (elem (m,n) pairs) it should return true. Sound right?

解决方案

Ignoring the helper method, the list comprehension you have will list out all pairs but the order of elements is a problem. You'll have a infinitely many pairs like (0, m) which are followed by infinitely many pairs like (1, m). Of course elem will forever iterate all the (0, m) pairs never reaching (1, m) or (2, m) etc.

I'm not sure why you have the helper method -- with it, you are only building a list of pairs like [(0,0), (1,1), (2,2), ...] because you've filtered on m = n. Was that part of the requirements?

Like @hammar suggested, start with 0 = m + n and list out the pairs (m, n). Then list pairs (m, n) where 1 = m + n. Then your list will look like [(0,0), (0,1), (1,0), (0,2), (1,1), (2,0), ...].

这篇关于haskell增量对的无限列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆