我有一个功能:
powerOf :: Int -> Int -> Int
示例操作系统用法:
*Main Data.List> powerOf 100 2
2
*Main Data.List> powerOf 100 5
2
我有两个问题。首先 - 为什么它不起作用:
map (powerOf 100) [2, 5]
我想得到 [2, 2]。
第二个问题。我试图创建 pariatl 函数。像这样的东西:
powerOfN :: Int -> Int
powerOfN num = powerOf num
以这种方式使用它:
let powerOf100 = powerOfN 100
powerOf100 2
powerOf100 5
但我收到错误消息:
simplifier.hs:31:15:
Couldn't match expected type `Int'
against inferred type `Int -> Int'
In the expression: powerOf num
In the definition of `powerOfN': powerOfN num = powerOf num
这里充满了可能的代码:
divided :: Int -> Int -> Bool
divided a b =
let x = fromIntegral a
y = fromIntegral b
in (a == truncate (x / y) * b)
listOfDividers :: Int -> [Int]
listOfDividers num =
let n = fromIntegral num
maxN = truncate (sqrt n)
in [n | n <- [1.. maxN], divided num n]
isItSimple :: Int -> Bool
isItSimple num = length(listOfDividers num) == 1
listOfSimpleDividers :: Int -> [Int]
listOfSimpleDividers num = [n | n <- listOfAllDividers, isItSimple n]
where listOfAllDividers = listOfDividers num
powerOfInner :: Int -> Int -> Int -> Int
powerOfInner num p power
| divided num p = powerOfInner (quot num p) p (power + 1)
| otherwise = power
powerOf :: Int -> Int -> Int
powerOf num p = powerOfInner num p 0
powerOfN :: Int -> Int
powerOfN num = powerOf num
powerOf 返回 num 中 p 的最大幂。例如:100 = 2 * 2 * 5 *5,所以 powerOf 100 2 = 2。10 = 2 * 5,所以 powerOf 10 2 = 1。
如何修复错误?谢谢。