Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 445
Steve3p0 Avatar asked May 06 '18 08:05

Steve3p0


3 Answers

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

like image 74
Lou Zell Avatar answered Nov 20 '22 15:11

Lou Zell


You can't just put any expression in a hs file.

As the error message says, you need a declaration here. For example:

main =
    print (fst (1,2)) >>
    print (snd (1,2))
like image 43
melpomene Avatar answered Nov 20 '22 14:11

melpomene


I am getting this error but the cause appears to be completely different from anything posted here. And the error message is not at all helpful.

Using Cabal version 3.6.2.0 with GHCI 8.10.7 on MacOS High Sierra (10.13) I'm working from this page: https://www.tutorialspoint.com/haskell/haskell_modules.htm specifically the "custom modules" section. There you can see the code I copied and pasted.

Besides the tutorial not mentioning I needed to add "other-modules: Custom" to myfirstapp.cabal, and besides the fact that the sample Custom.hs file includes "if x 'rem' 2 == 0" rather than "if x rem 2 == 0", here is the problem:

Indentation matters!

This line (inside the quotes) does NOT work "if x rem 2 == 0". This line DOES work " if x rem 2 == 0"!

Indenting by one space is the difference between success and failure.

I'm totally new to Haskell. I've programmed extensively in PHP, Javascript, and Applescript, and dabbled in a dozen others, and this is the first time I've seen white space matter. I assume this is commonly known amongst Haskell veterans, but it would certainly be nice if that was included prominently in the documentation.

like image 2
jwbaumann Avatar answered Nov 20 '22 14:11

jwbaumann