素数的懒惰列表 [英] Lazy List of Prime Numbers

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

问题描述

如何在Haskell中实现一个素数列表,以便他们可以被懒惰地检索?



我是Haskell的新手,想了解实用使用懒惰评估功能。

解决方案

下面是一个简短的Haskell函数,枚举

  primes :: [Integer] 
primes = sieve(2:[3,5 ..])
其中
sieve(p:xs)= p:sieve [x | x < - xs,x`mod` p> 0]

显然,这并不是Eratosthenes的Sieve(谢谢, Landei)。我认为这仍然是一个有启发意义的例子,表明你可以在Haskell中编写非常优雅的短代码,并显示如何选择错误的数据结构会严重影响效率。

How would one implement a list of prime numbers in Haskell so that they could be retrieved lazily?

I am new to Haskell, and would like to learn about practical uses of the lazy evaluation functionality.

解决方案

Here's a short Haskell function that enumerates primes from Literate Programs:

primes :: [Integer]
primes = sieve (2 : [3, 5..])
  where
    sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]

Apparently, this is not the Sieve of Eratosthenes (thanks, Landei). I think it's still an instructive example that shows you can write very elegant, short code in Haskell and that shows how the choice of the wrong data structure can badly hurt efficiency.

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

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