哈斯克尔列表理解寻找素数 [英] Haskell list comprehension for finding primes

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

问题描述

我试图使用列表推导尽可能简洁地查找小于某个整数 n 的所有素数。我正在学习Haskell,这只是一个练习。我想写一些东西:

  isqrt :: Integral a => a  - > 
isqrt = floor。 sqrt。 fromIntegral

primes :: Integral a => a - > [a]
素数n = [i | i < - [1,3..n],mod i k / = 0 | k

这当然不起作用。有没有一种方法可以在列表理解中获得列表理解?



这是我得到的错误:

 练习-99-1.hs:138:39:不在范围中:`k'

练习-99-1.hs:138:46 :
非法平行列表理解:使用-XParallelListComp

练习-99-1.hs:138:68:不在范围内:`i'



但是 - 我并不真正希望语法甚至是合法的: - )



意图是尽可能直接翻译: 素数n =奇数整数 i 小于 n 使得 i 不能被任何 k ,所有 k 在集合中: primes(isqrt i) - 或多或少。 (我希望我得到的是对的?)



谢谢!

>我在以下方面取得了一些进展:


$ b

primes: :积分a => a - > [a]
素数2 = [2]
素数n = 2:[i |如果(mod ik / = 0)then True else False)
(primes(isqrt i))]

有没有更简单的方法来编写lambda谓词?



编辑:是的,这要归功于评论中的评论!

  primes :: Integral a => a  - > [a] 
素数2 = [2]
素数n = 2:[i | i < - [3,5..n],all((/ = 0).mod i)(primes(isqrt i))]


I'm trying to find all the primes less than some integer n as concisely as possible, using list comprehensions. I'm learning Haskell, and this is just an exercise. I'd like to write something like:

isqrt :: Integral a => a -> a   
isqrt = floor . sqrt . fromIntegral

primes :: Integral a => a -> [a]  
primes n = [i | i <- [1,3..n], mod i k /= 0 | k <- primes (isqrt i)]

which of course doesn't work. Is there a way to have a list comprehension inside a list comprehension?

Here is the error I'm getting:

exercise-99-1.hs:138:39: Not in scope: `k'

exercise-99-1.hs:138:46:
    Illegal parallel list comprehension: use -XParallelListComp

exercise-99-1.hs:138:68: Not in scope: `i'

BUT - I wasn't really expecting the syntax to even be legit :-)

The intent was to translate as directly as possible: " primes n = the set of odd integers i less than n such that i is not divisible by any k, for all k in the set: primes (isqrt i)" - more or less. (I hope I got that right?)

Thanks!

解决方案

I made some progress with the following:

primes :: Integral a => a -> [a]  
primes 2 = [2]  
primes n = 2:[i | i <- [3,5..n], all (\k -> if (mod i k /= 0) then True else False) 
                                     (primes (isqrt i))]

Is there a shorter way to write the lambda predicate?

edit: Yes, there is, thanks to the remarks in the comments!

primes :: Integral a => a -> [a]  
primes 2 = [2]  
primes n = 2:[i | i <- [3,5..n], all ((/= 0) . mod i) (primes (isqrt i))]

这篇关于哈斯克尔列表理解寻找素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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