首页 > 解决方案 > “func :: String -> [Int]; func = read "[3,5,7]" 有什么问题?

问题描述

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

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

由于我有明确的类型注释,我希望[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]"
   |        ^^^^^^^^^^^^^^

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

标签: functionhaskelltypescompiler-errorstype-signature

解决方案


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

试试这个:

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

推荐阅读