Haskell compiler error: not in scope

Tag: haskell Author: lxsk1990 Date: 2009-10-22

I am trying to learn haskell by writing a simple file copy util:

main = do
         putStr "Source: "
         srcPath <- getLine
         putStr "Destination: "
         destPath <- getLine
         putStrLn ("Copying from " ++ srcPath ++ " to " ++ destPath ++ "...")
         contents <- readFile srcPath
    	 writeFile destPath contents
         putStrLn "Finished"

This gets me

GHCi, version 6.10.4: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( D:\Test.hs, interpreted )

D:\Test.hs:8:22: Not in scope: `contents' Failed, modules loaded: none. Prelude>

I don't understand that compiler error because the variable seems to be ok. What is wrong?

Here is a repro file: at rapidshare

Best Answer

It looks like you mixed tabs and spaces (just look at your question in "edit" view to see the issue). While your editor views the code evenly indented, the Compiler seems to have a different interpretation how wide a tab should be, resulting in the writeFile destPath contents line being additionally indented. So the source is interpreted like this:

  ...
  putStrLn ("Copying from " ++ srcPath ++ " to " ++ destPath ++ "...")
  contents <- readFile srcPath writeFile destPath contents
  putStrLn "Finished"

In this interpretation of the source code contents is used before it is created, so you get a compiler error.

To avoid these kind of errors best don't use tabs, or at least take additional care that you use them consistently.

Other Answer1

That looks correct. I just pasted that into a .hs file and :loaded it into GHCi. Works here and I have the same GHC version as you.

comments:

I have uploaded the hs-file that i use.