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が、コンパイラはガードがlowestDivisorHelperまたはに属しているかどうかを知りません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 に答える