Home > Software engineering >  Can't read from a file in haskell
Can't read from a file in haskell

Time:12-16

I have been trying to use the readFile syntax in haskell but when I try to do it i get an error which I don't know how to fix.

My code:

import System.Environment

maze_path = "maze2.txt"

get_maze :: String -> IO [String]
get_maze file = 
    do 
        x <- readFile file
        return (read x)

The error:

*** Exception: Prelude.read: no parse

This error is gotten from executing the function 'get_maze' with the 'mape_path' string.

I am just trying to get the full contents of the file into a regular string format, any help would be appreciated.

CodePudding user response:

The line

x <- readFile file

works as you assume and assigns the contents of the given file to the variable x as a String. The error is thrown by the read function.

The read function converts a String to a given output type. In your case, given the type get_maze :: String -> IO [String], Haskell determines that read must have the type String -> [String]. As a result, the text file is expected to contain a formatted array of strings, essentially what you would get by writing e.g. show ["Hello", "World"] (["Hello","World"]).

The file does not seem to be formatted in that way. If read can't parse an input, it will throw the error that you got above. There are more robust ways to parse stuff in Haskell, but I could imagine that your file is simply not formatted in that way and that you want to use a different function.

If you just want to get a list of lines, for example, there is the lines :: String -> [String] function in Haskell, which splits a string into a list of lines.

  • Related