Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell first steps compile error

I've just installed Haskell platform full with the installer from here https://www.haskell.org/platform/mac.html

Now, as the noob I am, i created a very simple program, just to see if it works:

f :: Int -> Int
f x = x + 2

but when i execute

runhaskell test.hs

it returns

test.hs:0:53: error:

• Variable not in scope: main :: IO a0

• Perhaps you meant ‘min’ (imported from Prelude)

if i run

ghc test.hs

it returns

The IO action ‘main’ is not defined in module ‘Main’

indicating just the first char of the first line "f"

like image 529
exrezzo Avatar asked Oct 17 '17 17:10

exrezzo


1 Answers

With your program you have not instructed Haskell what the program should do. You only have defined a function. That does not mean that Haskell will automagically call that function.

You need to define a function with a special name main (ghc has an option to specify another name, but let us ignore this for now). main is a function of the type IO a. It is a function that describes an action (IO) that is called when you execute the program.

Since you only defined a single function f, you probably want to test f.

So we can write a main:

main :: IO ()
main = print (f 2)

Now if add this to the program. The compiler will generate an executable that will execute main. Here main is quite simple: we instruct it to print the result of f 2. So it will print 4. We call main the entry point of the program.

You can also decide to run an interactive session instead. In that case you do not need an entry point, since you can decide in the interactive session what functions you will call.

You can for instance use ghci file.hs to start an interactive sesion, and run:

$ ghci testprogram.hs 
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( testprogram.hs, interpreted )
Ok, modules loaded: Main.
*Main> f 2
4

So now we have called f 2, and the interactive session automatically prints the result 4.

like image 100
Willem Van Onsem Avatar answered Oct 05 '22 15:10

Willem Van Onsem