haskell - 递归分解整数以及有关 Haskell 中函数的一些问题
问题描述
我刚从 Python 开始学习 Haskell,我有几个关于函数的问题。我编写了以下代码:
--generating prime list
primes = sieve [2..]
sieve (p:ps) = p : sieve [x | x <- ps, mod x p /= 0]
--factorising function
--takes an input of a number and a list of primes and outputs a list of its prime factors
factorise (n,ps)
| mod n head ps /= 0 = div n head ps : factorise (div n head ps, ps)
| otherwise = factorise (n,tail ps)
首先,当我尝试编译时,我收到一个与 相关的错误n
,说 I cannot construct the infinite type: a ~ [a] -> a
,这是为什么?
其次,虽然我理解创建无限列表背后的逻辑,但为什么不必明确说明函数sieve
的类型,类型是否隐含?对于factorise
功能,我必须这样做吗?
最后,是否有更简洁的方法来编写上述算法(我理解它非常有效)?
解决方案
我的解决方案(我忘了给出递归的基本情况以及其他一些更正):
--generating prime list
primes :: Integral a => [a]
primes = sieve [2..]
sieve :: Integral a => [a] -> [a]
sieve (p:ps) = p : sieve [x | x <- ps, mod x p /= 0]
--factorising function
--takes an input of a number and a list of primes and outputs a list of its prime factors
factorise :: Integral a => (a, [a]) -> [a]
factorise (n, ps)
| n == 1 = []
| mod n f == 0 = f : factorise (v, ps)
| otherwise = factorise (n, tail ps)
where
f = head ps
v = div n f
推荐阅读
- html - 页面滚动后标题变宽
- php - Laravel:hasManyThrough 关系中的未知列“ìtem_size_id”
- sql - Laravel - 嵌套选择(雄辩)
- java - 在不同的项目中使用包含变量的文件
- java - LinkList 节点跳过循环并移动到下一个参数
- javascript - 在 Create React App Typescript 中未读取 SetupProxy 文件
- oauth - Google OAuth 2.0 令牌如何计数?
- boto3 - Aws lamda 将所有 xmls 从存储桶移动到另一个存储桶 - Python
- powershell - 从 PowerShell 或 CMD 调用 SCCM
- python - 列表未使用 df.to_csv 写入 csv