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

6 haskell types compiler-errors function type-signature

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

func :: String -> [Int]
func = read "[3,5,7]"
Run Code Online (Sandbox Code Playgroud)

由于我有明确的类型注释,我希望[3,5,7]在加载模块test并调用funcghci时得到.但是,我得到了

    • 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]"
   |        ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时read "[3,5,7]" :: [Int],[3,5,7]按预期返回.我加载模块时为什么会出错?

chi*_*chi 10

您试图将字符串作为类型的函数String -> [Int]而不是列表来读取[Int].但是,read无法将字符串转换为函数.

试试这个:

myList :: [Int]
myList = read "[3,5,7]"
Run Code Online (Sandbox Code Playgroud)


Kar*_*ski 6

您的函数类型是,String -> [Int]但您没有指定其参数,因此编译器"认为"您要返回函数String -> [Int]而不是[Int].

你可能想要:

func :: String -> [Int]
func s = read s
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

func "[3,5,7]"
Run Code Online (Sandbox Code Playgroud)

要不就:

func :: String -> [Int]
func _ = read "[3,5,7]"
Run Code Online (Sandbox Code Playgroud)