2

我在以下构造中有烦人的语法错误:

isPrime n = if numOfDivisors n == 0 then True else False            
    where numOfDivisors n = length $ [x | x <- [2..ceiling (sqrt n)], n `mod` x == 0]

我该如何解决?我是 Haskell 的新手,所以我不知道[2..ceiling (sqrt n)].

谢谢(对不起我可怜的大脑)。

4

1 回答 1

10

您同时使用sqrtand modwith n--第一个需要浮点类型,后者需要整数类型。您可能想要后者,并改为使用sqrt (fromIntegral n)

其他一些不请自来的建议:

  • 没有可能的理由去做if foo then True else False。只需单独使用布尔表达式。

  • 函数参数在where子句的范围内,因此numOfDivisors不需要n作为参数。

  • 不要length用于检查列表是否为空。改为在除数列表上使用null

于 2012-12-20T21:51:19.047 回答