Search code examples
haskellio

Haskell Reading lines from File and print these with modifications


i want to read a file containing one word per line and print this file line by line, adding the length of the word at the end of the line.

So far i got to this solution and it drops errors with mismatching types.

I've tried this for several days now and I lost all faith. I am unable to wrap my head around Haskell.

I hope someone can help me.

Here is my code:

import System.IO


main :: IO ()
main = do

  file <- readFile "palindrom.txt"
  putStrLn (unlines $ showLength $ lines file)

showLength (x:xs) = (x concat "has length of" length x) (showLength xs)

Solution

  • Change it to

    showLength :: [[Char]] -> [[Char]]
    showLength (x:xs) = -- (x concat "has length of" length x) (showLength xs)
                concat [x, " has length of ", show (length x)] : showLength xs
    showLength  []  =  []
    

    and it will work. Your original code here does not make much sense in Haskell.

    concat :: [[a]] -> [a] is a built-in function which concatenates together all the lists in a given list:

    > concat [[1],[2,3],[4]]
    [1,2,3,4]
    
    > concat ["a"," b ", "123"]
    "a b 123"