在Haskell中输入:传递一个看起来很小的数字,但总是一个整数(类型别名)

Mar*_*ver 4 c haskell typing

我目前正在使用Haskell网站Gentle Introduction来学习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.
    }

}
Run Code Online (Sandbox Code Playgroud)

例如,如果您正在寻找10中的最高值,那么您可以通过说"最高(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 
Run Code Online (Sandbox Code Playgroud)

例如,如果你试图获得10中的最高素数,你可以用"greatPrime 10 2 1"来调用它,这样你就可以从2开始搜索,你当前最大的素数就是1.

我将不胜感激任何帮助 - 通过帮助类型别名,通用代码实现,甚至语法/代码阻止.我是haskell的新手,所以可能有一种写作方式更有意义; 但是,我不是在寻找像筛子一样的完整算法重写.谢谢你的时间.

ham*_*mar 11

/经营者具有类型(/) :: Fractional a => a -> a -> a,这意味着它仅适用于Fractional类型,如Float,DoubleRational,而不是整数.

使用div :: Integral a => a -> a -> a整数除法.

> 10 `div` 2
5
> 7 `div` 2
3
Run Code Online (Sandbox Code Playgroud)

还有quot,向零而不是负无穷大舍入:

> (-7) `div` 2
-4
> (-7) `quot` 2
-3
Run Code Online (Sandbox Code Playgroud)

  • @MarshallConover:他们将函数转换为运算符,因此`````div` 2```与`div 7 2`相同.同样,您可以使用括号将运算符转换为函数,因此`2 + 3`与`(+)2 3`相同. (5认同)
  • 注意`quot`比`div`快一点,因为它是直接在cpu上实现的运算符,`div`必须处理结果,因为它处理负面结果的方式不同.(类似`rem`比`mod`更快)当你在一个大循环中使用其中一个运算符时,差异是值得注意的. (2认同)