4

我目前正在使用Haskell 网站的 Gentle Introduction to Haskell学习 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)”来调用它 - 您正在寻找 10 中的最高质数,从 2 开始,以及当前最高质数in 是 1。当它第二次尝试将数字 5 作为除数时,它会返回,并看到 curDom 现在是 1。

问题是,当我在 Haskell 中尝试此操作时,在代码的第四行,我遇到了一个问题,即传递数字除以进入其中的素数 - 它似乎是分数 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

/运算符具有 type (/) :: Fractional a => a -> a -> a,这意味着它仅适用于、和等Fractional类型,而不适用于整数。FloatDoubleRational

用于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 回答