M2L1 Editing Haskell Source Code

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

FUNCTIONAL PROGRAMMING

MODULE 2 LESSON 1

EDITING HASKELL SOURCE CODE

 Creating main function


 Interacting with interpreter (ghci)
 Compiling a code with ‘stack ghci’

The first thing to do would be to open a text file. Call it test.hs


hs is the extension use for Haskell files.

You can simply create a main function.

If we now open up the Haskell interpreter we can load this file (using the :load and the
name of the file) and simply run the function.

A function declared as main is special to Haskell and GHC gives you the option of
running colon main (:main).

Haskell's expecting this kind of function to be of a specific type.

Here we see that the main function has to be an IO function which means that it will be
doing input and output and that it has no return value which is the meaning of the
empty parentheses.

We can edit the file and add the type declaration.


Now from the GHCI we can reload the file and confirm that we can still run that.

(This is just a duplicate of the screenshot above, where I put labels.)

We can define other functions within main (the greet is the other function)

If we reload this we can run the main function and we can also run the defined functions
by themselves.

We can also declare variables.

Result
You now know how to edit source code and run it interactively.

We can compile a file using a GHC.

And we can simply add the source code file (test.hs)

And we can see that it's created some intermediate files and an executable (test.o).

And if we run that from the command line we'll see that we have a program that can
output Howdy, World.

Now if we have a look at the file system we'll see that the program is 10 megabytes
large.

That's quite big for just a program that outputs a little bit of text.

One very simple thing we may want to do is to add the minus dynamic flag.
We do that by adding two dashes to say that the rest of what follows is options that we
pass to GHC (to the compiler itself) and dynamic.

So we want to link dynamically rather than including every single module that is shipped
with Haskell in our executable.

And if we have a look at the file that's been generated, it is only 12K.

End of this module.

You might also like