Could not match type `[] 'with` IO' - Haskell
I am new to Haskell. In this task, I am performing a split operation, but I am facing a problem due to an incorrect type match. I am reading data from a text file and the data is in table format. Ex. 1|2|Rahul|13.25.
In this format. Here |
is the delimiter, so I want to split the data from the delimiter |
and I want to print data from the 2nd column and 4th column, but I get an error like this
"Couldn't match type `[]' with `IO'
Expected type: IO [Char]
Actual type: [[Char]]
In the return type of a call of `splitOn'"
Here is my code ..
module Main where
import Data.List.Split
main = do
list <- readFile("src/table.txt")
putStrLn list
splitOn "|" list
Any help on this would be appreciated .. Thanks
source to share
Not Haskell, but it looks like a typical awk task.
cat src / table.txt | awk -F '|' '{print $ 2, $ 4}'
Back to Haskell, the best I can find is:
module Main where
import Data.List.Split(splitOn)
import Data.List (intercalate)
project :: [Int] -> [String] -> [String]
project indices l = foldl (\acc i -> acc ++ [l !! i]) [] indices
fromString :: String -> [[String]]
fromString = map (splitOn "|") . lines
toString :: [[String]] -> String
toString = unlines . map (intercalate "|")
main :: IO ()
main = do
putStrLn =<<
return . toString . map (project [1, 3]) . fromString =<<
readFile("table.txt")
If you are not reading a file, but from stdin, the function interact
might be useful.
source to share