Haskell: Parse error: module header, import declaration or top-level declaration expected

compiler-errorshaskell

I am saving some commands in a Haskell script in a .hs file while working thru a Haskell textbook. Here's a small example.

fst (1,2)
snd (1,2)

When I run these commands from the prelude in GHCi, they work fine. When I try to compile the .hs file with these two lines, I get the following:

ch4_test.hs:2:1: error:
    Parse error: module header, import declaration
    or top-level declaration expected.
  |
2 | fst (1,2)
  | ^^^^^^^^^
Failed, no modules loaded.

I've googled this error and can't find any explanation what I'm doing wrong.

Best Answer

From a newbie to future newbies: The interactive environment ghci would lead you to believe that you can punch some expressions into an .hs file and run the thing (in a similar fashion to languages like swift and ruby). This is not the case.

Haskell needs an entrypoint called main. Quoting:

Here is a simple program to read and then print a character:

main :: IO ()
main =  do c <- getChar
           putChar c

The use of the name main is important: main is defined to be the entry point of a Haskell program (similar to the main function in C), and must have an IO type, usually IO ()

Source: https://www.haskell.org/tutorial/io.html

Related Topic