24

我刚刚开始自学 Haskell。此代码应该进行素数分解:

divides :: Integer -> Integer -> Bool
divides small big = (big `mod` small == 0)

lowestDivisor :: Integer -> Integer
lowestDivisor n = lowestDivisorHelper 2 n
    where lowestDivisorHelper m n
        | (m `divides` n) = m  -- these should belong to lowestDivisorHelper
        | otherwise = lowestDivisorHelper (m+1) n

primeFactors :: Integer -> [Integer]
primeFactors 1 = []
primeFactors n
    | n < 1 = error "Must be positive"
    | otherwise = let m = lowestDivisor n
                  in m:primeFactors (n/m)

我在注释行上收到解析错误。我认为我的问题可能是lowestDivisorHelper有警卫,但编译器不知道警卫是否属于lowestDivisorHelperor lowestDivisor。我该如何解决这个问题?

我应该补充一点,我不想在顶层定义辅助函数以隐藏实现细节。导入文件不应该使用辅助函数。

4

1 回答 1

27
lowestDivisor :: Integer -> Integer
lowestDivisor n = lowestDivisorHelper 2 n where 
  lowestDivisorHelper m n
        | (m `divides` n) = m  -- these should belong to lowestDivisorHelper
        | otherwise = lowestDivisorHelper (m+1) n

您需要使用辅助函数开始一个新语句,以便通过比较来充分缩进警卫。(而且您还忘记了一个论点n。)这也可以:

lowestDivisor :: Integer -> Integer
lowestDivisor n = lowestDivisorHelper 2 n 
    where 
  lowestDivisorHelper m n
        | (m `divides` n) = m  -- these should belong to lowestDivisorHelper
        | otherwise = lowestDivisorHelper (m+1) n

但这不是:

lowestDivisor :: Integer -> Integer
lowestDivisor n = lowestDivisorHelper 2 n 
  where lowestDivisorHelper m n
        | (m `divides` n) = m  -- these should belong to lowestDivisorHelper
        | otherwise = lowestDivisorHelper (m+1) n

关键是|必须比函数名更靠右。

一般来说,只要它更靠右,开始一条新线就会继续前一条线。守卫必须从函数名称继续。

于 2012-11-11T00:27:54.487 回答