0
votes

I'm relatively new to Haskell and can't figure out what I'm doing wrong in this block.

The point of the block is to take a list and ask for an Int, which is then used as the index of the list element. If the value input isn't an Int, it results in an error and loops the block again.


returnIndex' :: [String] -> IO ()
returnIndex' xs = do
  putStrLn "Index Number:"
  n <- getLine
  att <- try(return(read n :: Int)) :: IO(Either SomeException Int)
  case att of 
    Left _ ->
      putStrLn "Has To Be Int" >> returnIndex' xs
    Right index ->
      print (xs!!index)

It compiles just fine, but when I try to run it, I get:

  • No instance for (Show ([String] -> IO ())) arising from a use of `print' (maybe you haven't applied a function to enough arguments?)
  • In a stmt of an interactive GHCi command: print it

The only print in the code is the last line, which looks pretty harmless to me. Isn't print essentially just putStrLn.show? Is the error that it takes [String] instead of just String?

Edit: Thank you for the comments but the problem inexplicably resolved itself, all I did was close and reopen the command prompt a few minutes later. I don't know the common stack overflow etiquette now, should I just delete my question?

1
Type errors are catched at compile time. So it looks like you do something wrong. Do you by any chance just run returnIndex', instead of returnIndex' ["List", "Of", "Values"]?Willem Van Onsem
Note that if you write someExpression, then implicitly, you write print someExpression, so the print is not from the function, but from the one in the ghci prompt.Willem Van Onsem
You are trying to evaluate a function, and asking GHCi to print that. E.g. if you enter succ in GHCi you get a similar error. You should pass its arguments as in succ 4 so that the final result can be shown. In your case, enter something like returnIndex' ["aa", "bb"]chi

1 Answers

0
votes

It appears you have loaded the file up in an interpreter then tried to call the function without any arguments:

$ cat so.hs
import Control.Exception (SomeException, try)

returnIndex' :: [String] -> IO ()
returnIndex' xs = do
  putStrLn "Index Number:"
  n <- getLine
  att <- try(return(read n :: Int)) :: IO(Either SomeException Int)
  case att of
    Left _ ->
      putStrLn "Has To Be Int" >> returnIndex' xs
    Right index ->
      print (xs!!index)
$ ghci so.hs
...
*Main> returnIndex'

<interactive>:3:1: error:
    • No instance for (Show ([String] -> IO ()))
        arising from a use of ‘print’
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it

You are trying to show the operation returnIndex'. Instead try applying the function to a list of strings:

*Main> returnIndex' ["hello", "amazing", "people"]
Index Number:
2
"people"