-1

I am trying to read from a file. I want to split each line from a file into its own string. I am thinking of using the lines command in order to make a list of Strings of all the lines. I then plan to use the words command to spilt each line into a list of words. However, I am very new to functional programming/Haskell, and I don't fully understand the syntax. So, to begin, how do you read each line from a file and store it?

I attempted the following code, but it does not compile.

main :: IO ()
main = do
  contents <- readFile "input.txt" 
  contents1 = lines contents
dvargasp
  • 61
  • 1
  • 5

1 Answers1

3

There are two reasons why it does not compile. First, let is absent, to quote GHC:

Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'

The other one is:

The last statement in a 'do' block must be an expression
  let contents1 = lines contents

After fixing both it compiles and runs:

main :: IO ()
main = do
  contents <- readFile "input.txt" 
  let contents1 = lines contents
  print contents1
bereal
  • 32,519
  • 6
  • 58
  • 104