【发布时间】:2020-05-02 23:46:31
【问题描述】:
我刚从 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相关的错误,说我cannot construct the infinite type: a ~ [a] -> a,这是为什么?
其次,虽然我了解创建无限列表背后的逻辑,但为什么不必显式声明函数 sieve 的类型,是隐含的类型吗?对于factorise 函数,我必须这样做吗?
最后,有没有更简洁的方法来编写上述算法(据我所知效率非常高)?
【问题讨论】:
-
提示:
mod n head ps需要一些括号...此外ps可以为空。 -
why do you not have to explicitly state the types of the function sieve, are the types implied?实际上,Haskell 具有类型推断功能,因此在编译代码时需要类型签名相对较少。但是,仍然强烈建议为此类顶级定义包含类型签名。它们可以更好地记录您的代码,并且通常会导致更易于理解的错误消息。 -
我同意 Robin,但想补充一点,包括显式类型声明也可以导致编译器捕获错误,否则它会完全错过。
-
新手添加不正确的类型签名也很常见,这会阻止编译器编译它自己会推断出正确类型的代码。
标签: haskell types primes prime-factoring type-signature