【发布时间】:2012-02-24 18:29:36
【问题描述】:
这是我计算斐波那契数的代码:
f' :: (Int -> Int) -> Int -> Int
f' mf 0 = 0
f' mf 1 = 1
f' mf n = mf(n - 2) + mf(n - 1)
f'_list :: [Int]
f'_list = map (f' faster_f') [0..]
faster_f' :: Int -> Int
faster_f' n = f'_list !! n
当 'n' 很小时它工作得很好。为了解决大数字的问题,我想将 Int-type 转换为 Integer:
f' :: (Integer -> Integer) -> Integer -> Integer
f' mf 0 = 0
f' mf 1 = 1
f' mf n = mf(n - 2) + mf(n - 1)
f'_list :: [Integer]
f'_list = map (f' faster_f') [0..]
faster_f' :: Integer -> Integer
faster_f' n = f'_list !! n
使用此代码我得到错误:
Couldn't match expected type `Int' with actual type `Integer'
In the second argument of `(!!)', namely `n'
In the expression: f'_list !! n
In an equation for `faster_f'': faster_f' n = f'_list !! n
好吧,我已经正确理解了列表中元素的索引不能是整数类型。 好的:
f' :: (Integer -> Integer) -> Integer -> Integer
f' mf 0 = 0
f' mf 1 = 1
f' mf n = mf(n - 2) + mf(n - 1)
f'_list :: [Integer]
f'_list = map (f' faster_f') [0..]
faster_f' :: **Int** -> Integer
faster_f' n = f'_list !! n
但现在我得到了错误:
无法匹配预期类型
Integer' with actual typeInt' 预期类型:整数 -> 整数Actual type: Int -> Integer In the first argument of `f'', namely `faster_f'' In the first argument of `map', namely `(f' faster_f')'
为什么?我该如何解决?
【问题讨论】:
-
从
Int切换到Integer不会不会让您的代码更快;事实上,我希望它会变慢...... -
问题不在于速度,而在于类型溢出。 fast_f' 100 - 与 Int 类型一起工作不正确
-
对不起,我的错误;我误读了您写的内容:s
标签: haskell