没有从字面上的'1'产生的Num字符串的实例 [英] No instance for Num String arising from the literal `1'
问题描述
main = do
putStrLn $ myLast [1,2,3,4]
myLast :: [a] - > a
myLast [x] = x
myLast(_:xs)= myLast xs
当我尝试运行此代码时,我收到以下消息:
没有针对从字面值'1'产生的(Num字符串)的实例
可能修复:为(Num字符串)添加一个实例声明
当我运行列表[1,2,3,4 ]。我没有指定类型,但它不适用于int。
。
你遇到的问题就是这个
Prelude>:t putStrLn
putStrLn :: String - > IO()
即该函数可以只处理字符串,而不处理数字。一个常见的解决方案是首先将要显示的内容转换为字符串: putStrLn(show x)
,但实际上这个组合存在一个更好的标准函数:
main = do
print $ myLast [1,2,3,4]
main = do
putStrLn $myLast [1,2,3,4]
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
When i try to run this code i get this message:
"No instance for (Num String) arising from the literal `1' Possible fix: add an instance declaration for (Num String)"
It runs well when I run with the list ["1","2","3,"4"]. I didn't specify the type but it doesn't work with ints.
"No instance for..." error messages are usually misleading.
The problem you have is simply this
Prelude> :t putStrLn
putStrLn :: String -> IO ()
i.e. that function can only deal with strings, not with numbers. An often-seen solution is to first translate the thing you want to show into a string: putStrLn (show x)
, but actually the combination exists as a much nicer standard function:
main = do
print $ myLast [1,2,3,4]
这篇关于没有从字面上的'1'产生的Num字符串的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!