在一个非常简单的模块test
中,我具有以下功能
func :: String -> [Int]
func = read "[3,5,7]"
由于我有显式类型注释,因此我在加载模块[3,5,7]
并在ghci中调用test
时会得到func
。但是,我得到了
• No instance for (Read (String -> [Int]))
arising from a use of ‘read’
(maybe you haven't applied a function to enough arguments?)
• In the expression: read "[3,5,7]"
In an equation for ‘func’: func = read "[3,5,7]"
|
11 | func = read "[3,5,7]"
| ^^^^^^^^^^^^^^
但是当我执行read "[3,5,7]" :: [Int]
时,将按预期返回[3,5,7]
。为什么当我加载模块时出现错误?
答案 0 :(得分:10)
您正在尝试根据类型String -> [Int]
而不是列表[Int]
读取字符串。但是,read
无法将字符串转换为函数。
尝试以下方法:
myList :: [Int]
myList = read "[3,5,7]"
答案 1 :(得分:7)
您的函数类型为String -> [Int]
,但是您没有指定其参数,因此编译器“认为”您想返回一个函数String -> [Int]
而不是[Int]
。
您可能想要:
func :: String -> [Int]
func s = read s
,然后将其用作:
func "[3,5,7]"
或者只是:
func :: String -> [Int]
func _ = read "[3,5,7]"