Haskell - 定义一个函数,在一个'where' [英] Haskell - defining a function with guards inside a 'where'

查看:290
本文介绍了Haskell - 定义一个函数,在一个'where'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始自学Haskell。这段代码应该做素因式分解:

I'm just starting out at teaching myself Haskell. This code is supposed to do prime factorisation:

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)

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

I get a parse error on the commented line. I think my problem might be that lowestDivisorHelper has guards, but the compiler doesn't know whether the guards belong to lowestDivisorHelper or lowestDivisor. How do I get around this?

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

Edit: I should add that I didn't want to define the helper function at the top level in order to hide the implementation detail. Importing the file shouldn't take the helper function with it.

推荐答案

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 。)
这也可以工作:

You need to start a new statement with your helper function for the guards to be sufficiently indented by comparison. (And you also forgot an argument, n.) This would also work:

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

关键在于 | 必须比函数名称更靠右。

The key point is that the | has to be further to the right than the function name.

一般而言,只要它开始一个新行继续前一行是更靠右的。守卫必须继续从功能名称。

In general, starting a new line continues the previous one as long as it is further to the right. The guards have to continue on from the function name.

这篇关于Haskell - 定义一个函数,在一个'where'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆