"func :: String -> [Int]; func = read "[3,5,7]有什么问题""

What's wrong with "func :: String -> [Int]; func = read "[3,5,7]""

在一个非常简单的模块中 test 我有以下功能

func :: String -> [Int]
func = read "[3,5,7]"

由于我有明确的类型注释,我希望在加载模块 test 并在 ghci 中调用 func 时得到 [3,5,7]。然而,我得到了

    • 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] 会按预期返回。为什么我加载模块时出现错误?

您正在尝试将字符串作为 String -> [Int] 类型的函数而不是列表 [Int] 来读取。但是,read不能将字符串转成函数。

试试这个:

myList :: [Int]
myList = read "[3,5,7]"

你的函数类型是 String -> [Int] 但你没有指定它的参数所以编译器 "thinks" 你想要 return 一个函数 String -> [Int] 而不是 [Int].

你可能想要:

func :: String -> [Int]
func s = read s

然后将其用作:

func "[3,5,7]"

或者只是:

func :: String -> [Int]
func _ = read "[3,5,7]"