【发布时间】:2010-12-05 13:54:19
【问题描述】:
我有一个函数:
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。
如何修复错误?谢谢。
【问题讨论】:
-
你能提供
powerOf的代码吗? -
powerOf似乎已损坏或命名错误。据我所知,100 的 2 次方是 10000。 -
我发布我所有的代码并解释powerOf。
-
它仍然可以正常工作 — ideone.com/2fOdW
-
这是我的错误。我正在尝试 map (powerOf 100) [1, 2, 5] 并得到无限递归。 ideone.com/kuGVM
标签: haskell currying partial-application