为什么这个代码返回空列表或失败?哈斯克尔 [英] Why this code return empty list or fail? Haskell

查看:106
本文介绍了为什么这个代码返回空列表或失败?哈斯克尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

primes :: [Int]
primes = sieve [2..]

sieve :: [Int] -> [Int]
sieve (p:xs)= p:sieve[x|x<-xs,x `mod` p /= 0]

f :: Int->Int
f n = head [x|x<-[0,(product (filter (<n) primes))..],x/=0,sum (map (x `mod`) [1..n]) == 0]






加载到GHCi
并键入f 20
失败...... plz help me


load into GHCi and type "f 20" fail...... plz help me

推荐答案

问题是用过滤器(< n)素数。由于素数是一个无穷大非常长的 1 列表,所以需要很长时间终止,因为它不知道那么(< n)最终会返回 False 继续检查整个列表。

The problem is with filter (< n) primes. Since primes is an infinite very long1 list, this takes a long time to terminate since it doesn't know that (< n) will eventually return False for all primes past a certain point in the list, so it has to keep checking the entire list.

> filter (< 20) primes
[2,3,5,7,11,13,17,19^CInterrupted.

使用 takeWhile(< n)素数取而代之。

Use takeWhile (< n) primes instead.

> takeWhile (< 20) primes
[2,3,5,7,11,13,17,19]

1 由于 [Int] 类型,它是有限的。如果它是 [Integer] ,它将是无限的。

1 It's finite because of the type [Int]. If it was [Integer], it would be infinite.

这篇关于为什么这个代码返回空列表或失败?哈斯克尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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