Can I split a list in Haskell using a delimiter?

Viewed 126

I have a text file which contains the following:

1 kg g
5000 m km
98.6 f c

I am supposed to read the file and convert the number from the first unit to the second and write the outputs in another text file, so the end result should be:

1000
5
37

My code so far is:

import System.IO  
import Control.Monad

main = do
    contents <- readFile "Readings.txt"
    let ls = lines contents
    print $ ls


    when (length contents > 0) $
        writeFile "Outputs.txt" contents

Output:

["1 kg g\r","5000 m km\r","98.6 f c\r"]

Currently I am trying to split the list ls by spaces so I can have each element in the row alone. Is my thinking process right? or can I approach this in a better way?

1 Answers

The standard words function will split on spaces:

> words "1 kg g"
["1","kg","g"]

For other delimiters, there is the Data.List.Split module from the split library.


To get rid of the \r from your DOS-format text file, use something like the following instead of readFile:

main = done
    handle <- openFile "Readings.txt"
    hSetNewlineMode handle universalNewlineMode
    contents <- hGetContents handle
    ...
Related