Search code examples
haskellfunctional-programmingblockmessagereadfile

Unexpected do block in function application involving ReadMode what does mean this message?


This function reads a String and concatenates to a txt file

adicionaEmListaDeCategorias :: [Char] -> IO() 
adicionaEmListaDeCategorias categoria = do
    file <- openFile ("listagemCategorias.txt") ReadMode
    categorias <- hGetContents file
    let categoria1 = (read categorias :: [Char]) ++ categoria
    hClose file
    file2 <- openFile ("listagemCategorias.txt") WriteMode
    hPutStr file2 (categoria)
    hFlush file2
    hClose file2

but I'm receiving this error message:

main.hs:190:41: error:
    Unexpected do block in function application:
        do file <- openFile ("listagemCategorias.txt") ReadMode
    You could write it with parentheses
    Or perhaps you meant to enable BlockArguments?
    |
190 | adicionaEmListaDeCategorias categoria = do
    |                                         ^^...

Solution

  • as I said in the comment - the issue is that you had intended the first line with a tab

    this one works:

    adicionaEmListaDeCategorias :: [Char] -> IO()
    adicionaEmListaDeCategorias categoria = do
        file <- openFile "listagemCategorias.txt" ReadMode
        categorias <- hGetContents file
        let categoria1 = (read categorias :: [Char]) ++ categoria
        hClose file
        file2 <- openFile "listagemCategorias.txt" WriteMode
        hPutStr file2 categoria
        hFlush file2
        hClose file2
    

    but Haskell will give you an warning because you did not use categoria1 and I think you'll want this:

    adicionaEmListaDeCategorias :: [Char] -> IO()
    adicionaEmListaDeCategorias categoria = do
        file <- openFile "listagemCategorias.txt" ReadMode
        categorias <- hGetContents file
        let categoria1 = (read categorias :: [Char]) ++ categoria
        hClose file
        file2 <- openFile "listagemCategorias.txt" WriteMode
        hPutStr file2 categoria1
        hFlush file2
        hClose file2
    

    (write the concatenated version)


    also based on your problem description I think your version will not do what you expected (the read will fail and you don't need it):

    adicionaEmListaDeCategorias :: [Char] -> IO()
    adicionaEmListaDeCategorias categoria = do
        file <- openFile "listagemCategorias.txt" ReadMode
        fileContent <- hGetContents file
        hClose file
        let newFileContent = fileContent ++ categoria
        file2 <- openFile "listagemCategorias.txt" WriteMode
        hPutStr file2 newFileContent
        hFlush file2
        hClose file2