【问题标题】:What's wrong with "func :: String -> [Int]; func = read "[3,5,7]""“func :: String -> [Int]; func = read "[3,5,7]" 有什么问题
【发布时间】:2019-07-18 19:21:43
【问题描述】:

在一个非常简单的模块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] 会按预期返回。为什么我在加载模块时出现错误?

【问题讨论】:

  • cd str = [ (fromEnum d) - 48 | d <- str, elem d '0'..'9']] 将采用任何形式的单个数字字符串,cd "13579"cd "[2,3,5,7]"cd " 2 3 5"

标签: function haskell types compiler-errors type-signature


【解决方案1】:

你的函数类型是String -> [Int],但你没有指定它的参数,所以编译器“认为”你想要返回一个函数String -> [Int]而不是[Int]

你可能想要:

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

然后将其用作:

func "[3,5,7]"

或者只是:

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

【讨论】:

    【解决方案2】:

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

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2019-06-11
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-05-01
      相关资源
      最近更新 更多