c - 在 Haskell 中键入 : Passing a number that looks fractional, 但始终是整数(类型别名)

标签 c haskell typing

我目前正在使用 Gentle Introduction to Haskell website 学习 Haskell ,我在第 4 节的中途休息了一下,以测试我的知识。我正在尝试实现我在使用 C 语言时使用的“合数中最大素数”函数,但我在使用 Haskell 的打字系统时遇到了问题。我正在尝试传递一个看起来像小数 Int 的数字,但因为我使用模数来检查它是否可整除,所以我知道将计算为 Int。这是上下文:

C:我已经对它进行了 super 注释以防它不清楚,但代码应该相当简单。

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 开始,并且当前最大的素数是 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 的新手,所以可能有一种更有意义的写法;但是,我并不是在寻找像筛子一样的完整算法重写。感谢您的宝贵时间。

最佳答案

/ 运算符的类型为 (/)::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

关于c - 在 Haskell 中键入 : Passing a number that looks fractional, 但始终是整数(类型别名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572939/

相关文章:

使用指针连接两个数组(提供 C 代码)

haskell - 获取错误 Prelude.read : no parse

c - 如何选择合适的 Haskell C 类型?

JavaScript 类型。试图了解它的幕后工作原理

python - Python 3.6 中的通用 NamedTuple

python - 如何为类型参数设置 python 类型

c++ - 防止默认点击事件 (WinAPI)

c - 当从纯 C 切换到使用 Numpy 对象的 C 时,看似无意义的运行时间会增加

c - C中的结构继承

haskell - 使用foldl时如何获取列表中元素的索引