dem*_*mas 0 haskell currying partial-application
我有一个功能:
powerOf :: Int -> Int -> Int
Run Code Online (Sandbox Code Playgroud)
示例os用法:
*Main Data.List> powerOf 100 2
2
*Main Data.List> powerOf 100 5
2
Run Code Online (Sandbox Code Playgroud)
我有两个问题.首先 - 为什么它不起作用:
map (powerOf 100) [2, 5]
Run Code Online (Sandbox Code Playgroud)
我想得到[2,2].
第二个问题.我试图创建pariatl函数.像这样的东西:
powerOfN :: Int -> Int
powerOfN num = powerOf num
Run Code Online (Sandbox Code Playgroud)
使用它这样的方式:
let powerOf100 = powerOfN 100
powerOf100 2
powerOf100 5
Run Code Online (Sandbox Code Playgroud)
但我收到了错误消息:
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
Run Code Online (Sandbox Code Playgroud)
这里有很多代码:
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
Run Code Online (Sandbox Code Playgroud)
powerOf返回p的最大功率p.例如:100 = 2*2*5*5,因此powerOf 100 2 = 2. 10 = 2*5,因此powerOf 10 2 = 1.
如何修复错误?谢谢.
使用您的代码,除了powerOfN功能.我不能重现你的问题map (powerOf 100) [2,5].
*Main> map (powerOf 100) [2,5]
[2,2]
Run Code Online (Sandbox Code Playgroud)
你有任何错误吗?
关于你的第二个问题:
powerOfN :: Int -> Int
powerOfN num = powerOf num
Run Code Online (Sandbox Code Playgroud)
类型签名不正确.
powerOfN取一个整数并返回一个取整数并返回整数的函数.
所以类型签名应该是
powerOfN :: Int -> (Int -> Int)
Run Code Online (Sandbox Code Playgroud)
这是相同的(感谢delnan确认):
powerOfN :: Int -> Int -> Int
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
367 次 |
| 最近记录: |