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

  • A+
Category:Languages

In a very simple module test where I have the following function

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

Since I have explicit type annotations, I expect to get [3,5,7] when I load the module test and call func in ghci. However, I got

    • 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]"    |        ^^^^^^^^^^^^^^ 

But when I do read "[3,5,7]" :: [Int], [3,5,7] is returned as expected. Why an error was raised when I loaded the module instead?

 


Your function type is String -> [Int] but you didn't specify its argument so the compiler "thinks" that you want to return a function String -> [Int] instead of [Int].

You probably want:

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

and then use it as:

func "[3,5,7]" 

or just:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: