File processing-Haskell

1k views Asked by At

How can I implement in haskell the following:

  1. I receive an input file from the command line. This input file contains words separated with tabs, new-lines and spaces.
  2. I have to replace these elements (tabs, new-lines and spaces) with commas.
  3. And then write the result to a file called output.txt.

Any help is much appreciated. My haskell skills still developing.


So far I've got this code:

    processFile::String->String
    processFile [] =[]
    processFile input =input

    process :: String -> IO String
    process fileName = do
    text <- readFile fileName
    return (processFile text)

    main :: IO ()
    main = do
    n <- process "input.txt"
    print n

In processFile function I should process the text from the input file.

1

There are 1 answers

0
dflemstr On BEST ANSWER

You can use the getArgs function to read arguments on the command line. For example:

import System.Environment (getArgs)

main = do
  args <- getArgs
  case args of
    [arg] -> putStrLn $ "You gave me one arg: " ++ arg
    _     -> putStrLn $ "You gave me " ++ show (length args) ++ " arguments."

You can use the readFile function to read a file.

contents <- readFile "test.txt"
putStrLn contents -- Prints the contents of the file

You can use the writeFile function to write a file:

writeFile "test2.txt" "Some file data\n" -- Writes the data to the file

Tabs, newlines and spaces can be called whitespace, or word separators. The words function converts a string into a list of words.

print $ words "some text with\nmany words"
-- prints ["some", "text", "with", "many", "words"]

The intersperse function inserts a separator between each element of a list:

import Data.List (intersperse)

main =
  print $ intersperse '.' ["some", "text", "with", "many", "words"]
  -- prints "some.text.with.many.words"

You can also look at the intercalate function if you need longer separators.


These are all of the tools that you need for your program, I think that you can figure out the rest. Good luck!