4

私は現在、Haskellの穏やかな紹介のWebサイトを使用してHaskellを学習しています。そして、セクション4の途中で休憩して、知識をテストしました。Cで作業していたときに使用した「合成数の最大素数」関数を実装しようとしていますが、Haskellのタイピングシステムに問題があります。分数のIntのように見える数値を渡そうとしていますが、モジュラスを使用して除算可能かどうかを確認したため、Intに評価されることがわかります。コンテキストは次のとおりです。

C:不明な点がある場合に備えて、コメントを付けましたが、コードはかなり単純なはずです。

int highest(long currDom, long lastLargest, long currMax)
/* This is a recursive function that starts at the lowest prime number, 2,
 * and divides into currMax. If a division operation is even - modulus returns 0 -
 * then the prime number in the division is saved as "lastLargest," and the
 * function calls itself again, with MAX now passed as MAX/lastLargest. Otherwise,
 * the function is called with currMax remaining the same value, and the
 * current denominator to try (currDom) incremented by one.
 */
{
    if (currDom > currMax)   //end result - when the current value of MAX is less
        return lastLargest;  //than the value of the denominator we're trying, we're done
    else
    {
        if (currMax % currDom == 0)      //if modulus succeeds, try again with Max/currDom
            return highest(currDom, currDom, currMax/currDom);  //denominator is kept the same incase
        else                                                    //it goes into MAX multiple times -e.g. 2 into 8 
            return highest(currDom+1, lastLargest, currMax);    //else, try the next denominator.
    }

}

たとえば、10で最高の素数を探している場合は、「highest(10、2、1)」と言ってこれを呼び出します。2から始まる10の最高の素数と、現在の最高の素数を探しています。数は1です。2回目の除数として5を試し、curDomが1になっていることを確認すると戻ります。

問題は、Haskellでこれを試してみると、コードの4行目で、数値を素数で割った値を渡すという問題が発生することです。これは、分数のIntのように見えますが、すでにモジュラスでチェックされていますが、通常のIntに解決されることはわかっています。これが私が使っているコードです:

greatestPrime                                                   :: Int -> Int -> Int -> Int
greatestPrime num curPrime greatest | (curPrime > num)          = greatest
greatestPrime num curPrime greatest | (mod num curPrime) > 0    = greatestPrime num (curPrime+1) greatest 
greatestPrime num curPrime greatest | (mod num curPrime) == 0   = greatestPrime (num/curPrime) curPrime greatest 

たとえば、10で最高の素数を取得しようとしている場合、これを「greatestPrime 10 2 1」と呼ぶと、2から検索を開始し、現在の最大の素数は1になります。

型のエイリアシング、一般的なコードの実装、さらには構文/コードのブロックのいずれかを支援することで、これについて助けていただければ幸いです。私はhaskellを初めて使用するので、もっと意味のあるこれを書く方法があるかもしれません。しかし、私はふるいのような完全なアルゴリズムの書き直しを探していません。御時間ありがとうございます。

4

1 に答える 1

11

/演算子にはタイプがあります。これは、整数ではなく、、、などのタイプ(/) :: Fractional a => a -> a -> aでのみ機能することを意味します。FractionalFloatDoubleRational

div :: Integral a => a -> a -> a整数除算に使用します。

> 10 `div` 2
5
> 7 `div` 2
3

quot負の無限大ではなくゼロに向かって丸めるもあります。

> (-7) `div` 2
-4
> (-7) `quot` 2
-3
于 2012-03-05T19:53:50.047 に答える