停止ghci与列表理解 [英] Stoppage ghci with list comprehension

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

问题描述

我是Haskell的新手。
以下列表的理解力不够好。 ghci停止它的输出。 (在输入'7'后,ghci停止很长时间。)

I'm new to Haskell. Following list comprehension dose not work good. ghci stop it's output. (after type '7', ghci stop long long time.)

Prelude Data.Numbers.Primes> [x | x <- primes, x <= 10]
Loading package array-0.4.0.1 ... linking ... done.
Loading package deepseq-1.3.0.1 ... linking ... done.
Loading package old-locale-1.0.0.5 ... linking ... done.
Loading package time-1.4.0.1 ... linking ... done.
Loading package random-1.0.1.1 ... linking ... done.
Loading package Numbers-0.2.1 ... linking ... done.
[2,3,5,7^Z
[2]+  Stopped                 ghci

为什么ghci停止工作,我该如何解决它?
谢谢。

Why ghci stop its working and how can I fix it? Thank you.

推荐答案

问题是GHCi无法知道您的 primes 是有序的。可能在 primes 之后的一个元素小于 10 之后,它必须仍然包含在输出?这就是为什么ghci只打印结果的第一个元素( [2,3,4,7 ),但不是整个结果。如果您只想 ,那么您可以使用 takeWhile ,它遇到一个与谓词不匹配的数字后停止:

The problem is that GHCi can't know that your list of primes is ordered. Maybe after 1000000000000000 elements of primes, there comes some element that is smaller than 10, so it must be still included in the ouput? That's why ghci only prints the first elements of the result ([2,3,4,7), but not the whole result. If you only want those, you can use takeWhile, which stops after it encounters a number that doesn't match the predicate:

> takeWhile (<= 10) primes
[2,3,5,7] -- takeWhile stops after it encounters 7, because the predicate becomes false

> filter (<= 10) primes
[2,3,5,7  -- filter cannot stop, because there might still be a number later in the list that satisfies the predicate. This is what the list comprehension does. 

这篇关于停止ghci与列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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