2

Hi guys,

I'm parsing a text file which look like this:

114.474998474121 15.7440004348755 25.806999206543 -873 172 182 188 
114.46199798584 15.7419996261597 25.8799991607666 -1396 180 192 205 

And wish it can read as like this:

[[114.475,15.744,25.807,-873.0,172.0,182.0,188.0],
[114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]]

Currently my code for this text parsing doesn't give that. Here is my code:

main = do
    text <- readFile "mytext.txt" 
    let
        pcVal = map read (words text) :: [Float]
    print pcVal
    return ()

This code parsed all the text as a single list like this:

[114.475,15.744,25.807,-873.0,172.0,182.0,188.0,
114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]

I couldn't find how to take the whole single line (in text file) as a list, and the second line as another list till end of the file. Appreciate if somebody have experience in this. Thanks.

2
  • 1
    I assume you are a beginner - one tipp for the future, when you know a bit more haskell; revisit this exercise and implement a parser instead of just having a listof list of double values. Commented Dec 4, 2017 at 15:56
  • yes @epsilonhalbe, I'm a beginner and start to like this language. I will take your advise for the future. thanks! Commented Dec 5, 2017 at 8:54

2 Answers 2

7

You can use the lines function; for example map words $ lines text.

This would also be a good time for a helper function, ie

let parse :: String -> [Float]
    parse line = map read $ words line
    pcVal = map parse $ lines text
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Dan, I've tried but some bug in String - Char things. A bit of edit then it works! I post the answer below.
@SirDK I think the type annotation I've added should help.
0

Thanks Dan for suggesting lines as the solution. Here is the code that works fine with my question:

main = do
    text <- readFile "mytext.txt" 
    let
        readparse txtLines = map read txtLines :: [Float]
        parse txtLines = map (words) (lines txtLines)
        pcval = map readparse (parse text) 
    print pcVal
    return ()

Hope it help others too. Thanks and cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.