[英]Haskell Int to String
我知道这个问题以前曾出现过,但是出于某种原因, 这个问题的答案对我不起作用。 我的示例是以下代码:
fiblist = 0 : 1 : (zipWith (+) fiblist (tail fiblist))
fib :: (Integral a) => a -> String
fib n
| n < 10000 = show (fiblist !! n)
| otherwise = error "The number is too high and the calculation might freeze your machine."
我试图将索引n
处的元素转换为String,以便该函数符合其签名,但是出现以下错误:
MyLib.hs:63:34:
Couldn't match expected type ‘Int’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for fib :: Integral a => a -> String
at MyLib.hs:61:8
Relevant bindings include
n :: a (bound at MyLib.hs:62:5)
fib :: a -> String (bound at MyLib.hs:62:1)
In the second argument of ‘(!!)’, namely ‘n’
In the first argument of ‘show’, namely ‘(fiblist !! n)’
Failed, modules loaded: none.
那么我该如何转换呢?
编辑#1:
我知道命令行选项+RTS -M256m -K256m
等等,但是它们似乎不适用于此代码,如果n
太高,它仍然会占用我几乎所有的内存。 对于无限列表的length
,行为不同,那里的命令行参数起作用并停止执行代码。
编辑#2:
我找到了一种导入genericIndex
:
import Data.List
我想和这里显示的一样。
现在,当我使用以下代码时:
fib :: (Integral a) => a -> String
fib n
| n < 10000 = genericIndex fiblist n
| otherwise = error "The number is too high and the calculation might freeze your machine."
我收到以下错误:
MyLib.hs:64:11:
No instance for (Num String) arising from the literal ‘0’
In the first argument of ‘(:)’, namely ‘0’
In the expression: 0 : 1 : (zipWith (+) fiblist (tail fiblist))
In an equation for ‘fiblist’:
fiblist = 0 : 1 : (zipWith (+) fiblist (tail fiblist))
Failed, modules loaded: none.
由于您声称fib
在Integral
所有实例上都是多态的,因此最简单的解决方法可能是从使用(!!)
切换为使用genericIndex
,它们具有以下类型签名:
(!!) :: [a] -> Int -> a
genericIndex :: Integral i => [a] -> i -> a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.