Haskell中的c-Typeing:传递一个看起来是分数的数字,但它总是一个Integer(类型别名)



我目前正在使用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中的最高素数,你会说"最高(10,2,1)"——你在寻找从2开始的10中的最素数,而这个数字中当前的最高素数是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中的最高素数,你会把它称为"greaterestPrime 10 2 1",这样你就可以从2开始搜索,你现在的最大素数就是1。

如果能提供任何帮助,我将不胜感激——无论是帮助处理类型别名、通用代码实现,还是语法/代码阻塞。我是哈斯克尔的新手,所以可能有一种写这篇文章的方式更有意义;然而,我并不是在寻找像筛子一样的完整算法重写。谢谢你抽出时间。

/运算符的类型为(/) :: Fractional a => a -> a -> a,这意味着它只适用于FloatDoubleRationalFractional类型,而不适用于整数。

使用div :: Integral a => a -> a -> a进行整数除法。

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

还有quot,它向零而不是负无穷大取整:

> (-7) `div` 2
-4
> (-7) `quot` 2
-3

最新更新