哈斯克尔名单冻结 [英] Haskell list frozen

查看:119
本文介绍了哈斯克尔名单冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,并试图了解一些事情。如果我做了以下,我收到一个问题:

  list1 = [1 ..] 
list2 = [x | x< - list1,x< = 4]
print list2

code> [1,2,3,4- 。它没有末端括号,所以就好像列表正在加载或冻结一样。这是它的样子:

  Prelude> print list2 
[1,2,3,4

这是怎么回事? / p> 你知道列表单调递增,但Haskell不知道。使用 takeWhile ,而不是列表理解,以便在找到大于4的值时可以停止评估 list1

 > list1 = [1 ..] 
> list2 = takeWhile(< = 4)list1
> print list2
[1,2,3,4]


I'm new to Haskell and playing around trying to understand a few things. If I do the following I receive a problem:

list1 = [1..]
list2 = [x | x <- list1, x <= 4]
print list2

which returns [1,2,3,4. There isn't an end bracket on it, so it is as if the list is loading or frozen. Here is how it looks:

Prelude> print list2
[1,2,3,4

What is going on here?

解决方案

You know that the list is monotonically increasing, but Haskell does not. Use takeWhile, instead of a list comprehension, so that list1 can stop being evaluated once you find a value greater than 4.

> list1 = [1..]
> list2 = takeWhile (<= 4) list1
> print list2
[1,2,3,4]

这篇关于哈斯克尔名单冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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