Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using main in a Haskell file

I've done a fair bit of programming in haskell using GHCI however our next assignment requires us to use just GHC to compile and test our code.

Because of how ghci works compared to ghc you apparently need to use a main function and the ghc looks for this function in your code.

My question is, if Haskell promotes type safety and no side-effects unless within an IO action, why does the main part of any haskell program have to be an IO action?

Forgive me if I'm not understanding something fundamental, I just couldn't find any resources which ultimately explains this.

like image 980
Bradley Avatar asked Dec 01 '22 17:12

Bradley


2 Answers

If your main function is not an IO action, then all it can do is produce a result. Since Haskell is lazy, this (usually) means that it just produces a promise that the computation will be performed, but it won't compute it until it needs to be used. Since the usual way to ensure something is computed is to print that value out, or send it over a network, save it to disk, or use it for some other kind of IO, your result won't be computed and the program would simply exit. Imagine a fake program like

main :: Int
main = 1 + 1

Suppose you could compile and run this, what would you expect to happen? Nothing gets printed, nothing is asking for the result of main, all that Haskell can do with this is create the promise that 1 + 1 will be computed at some point then exit the program. Basically, you can't do anything interesting at the top level without IO, and since we want programs to do interesting things we need our top level to be an IO action.

like image 94
bheklilr Avatar answered Dec 05 '22 06:12

bheklilr


Put simply, running a program is a side-effect. This is why the top-level function is an I/O action.

An ideal Haskell program is a large chunk of pure code with a thin I/O "skin" around it.

like image 38
MathematicalOrchid Avatar answered Dec 05 '22 04:12

MathematicalOrchid