【问题标题】:Haskell - defining a function with guards inside a 'where'Haskell - 在“where”中定义一个带有守卫的函数
【发布时间】:2012-10-30 21:53:35
【问题描述】:

我刚刚开始自学 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 有守卫,但编译器不知道守卫是属于lowestDivisorHelper 还是lowestDivisor。我该如何解决这个问题?

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

【问题讨论】:

  • "导入文件时不应使用辅助函数。"在这种情况下,不要导出它。

标签: haskell where-clause parse-error


【解决方案1】:
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

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

一般来说,只要它更靠右,开始一个新行就会继续上一行。守卫必须从函数名继续。

【讨论】:

  • 啊,我只是在写评论说你的最后一个例子很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 2020-05-03
  • 1970-01-01
  • 2012-04-01
  • 2016-07-31
相关资源
最近更新 更多