5
Prelude Data.Set> :load hello
[1 of 1] Compiling Main             ( hello.hs, interpreted )

hello.hs:11:11: parse error on input `<-'
Failed, modules loaded: none.
Prelude Data.Set> h <- IO.openFile "testtext" IO.ReadMode
Prelude Data.Set> 

The same line [h <- IO.openFile "testtext" IO.ReadMode] inside hello.hs throws the error. How do i fix this? What am I doing wrong?

[EDIT] Source and output: http://pastebin.com/KvEvggQK

3
  • If Oswalds answer isn't helping you will probably need to show more code! Though, it seems it should solve your problem. Commented Dec 19, 2010 at 10:31
  • hi, what do i import to enable I/O? Commented Dec 19, 2010 at 10:57
  • i guess that line works inside Prelude because its also a part of the IO monad? Okay, i'll go read up first. Commented Dec 19, 2010 at 11:18

2 Answers 2

8

You can only use <- inside a do-block¹ (which you're implicitly in in GHCI, but not in Haskell files).

In a Haskell file, you're only allowed to write bindings using =.

What you could do is put the following in the Haskell file:

myHandle = do h <- IO.openFile "testtext" IO.ReadMode
              return h

Though if you think about that for a bit, this is just the same as:

myHandle = IO.openFile "testtext" IO.ReadMode

However this way myHandle is still wrapped in IO and you'll need <- (or >>=) in ghci to unwrap it.

You can't write a Haskell file in such a way that just loading the file, will open testtext and give you the file handle.


¹ Or a list comprehension, but there the right operand of <- needs to be a list, so that has nothing to do with your situation.

Sign up to request clarification or add additional context in comments.

Comments

-2

Try

[h | h <- IO.openFile "testtext" IO.ReadMode]

2 Comments

This is completely wrong. You can't use IOs as the right operand to <- in a list comprehension.
My answer is at most partially wrong: [h <- IO.openFile "Copy Bin.txt" IO.ReadMode] produces a parse error, [h | h <- IO.openFile "Copy Bin.txt" IO.ReadMode] does not produce a parse error. Depending on the definition of IO.openFile it might not produce any error at all. Granted, it produces type error when the most common definition is used.

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.