user40551
user40551

Reputation: 365

Haskell Read from file and parse string into words

When in ghci mode I can type this line :

map read $ words "1 2 3 4 5" :: [Int]

and get [1,2,3,4,5]

When I make a file named splitscan.hs containing this line:

    map read $ words scan :: [Float]

I get this error:

[1 of 1] Compiling Main ( splitscan.hs, splitscan.o )

splitscan.hs:1:1: error:
    Invalid type signature: map read $ words str :: ...
    Should be of form <variable> :: <type>
  |
1 | map read $ words str :: [Float]
  | ^^^^^^^^^^^^^^^^^^^^

When I do this:

import System.IO

main = do
    scan <- readFile "g924310_b1_copy.txt"
    map read $ words scan :: [Float]
    putStr scan

I get :

readscan.hs:5:5: error:
    • Couldn't match type ‘[]’ with ‘IO’
      Expected type: IO Float
        Actual type: [Float]
    • In a stmt of a 'do' block: map read $ words scan :: [Float]
      In the expression:
        do scan <- readFile "g924310_b1_copy.txt"
             map read $ words scan :: [Float]
           putStr scan
      In an equation for ‘main’:
          main
            = do scan <- readFile "g924310_b1_copy.txt"
                   map read $ words scan :: [Float]
                 putStr scan

The question is, how do implement the ghci line such that I can get all the words from the scan and make a list of them that I can later fit regressions, add constants to etc.

Upvotes: 1

Views: 1172

Answers (2)

user8174234
user8174234

Reputation:

I would do the following:

floats :: String -> [Float]
floats = fmap read . words

main :: IO ()
main = print =<< fmap floats readFile "g924310_b1_copy.txt"

Upvotes: 0

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

In Haskell, variables are immutable. So map read $ words scan doesn't change the variable scan; it returns a new value. You need to use this new value if you want to do something with it.

import System.IO

main = do
    scan <- readFile "g924310_b1_copy.txt"
    let scan' = map read $ words scan :: [Float]
    print scan'

Upvotes: 6

Related Questions