1

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.

1
  • Wouldn't use scan as a variable name as it resembles too much to scanl, scanr. Commented Jan 14, 2018 at 19:55

2 Answers 2

6

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'
Sign up to request clarification or add additional context in comments.

Comments

0

I would do the following:

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

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

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.