Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a script to ghci?

Tags:

haskell

I'm just starting learning Haskell, and having a hard time understanding the 'flow' of a Haskell program.

For example in Python, I can write a script, load it to the interpreter and see the results:

def cube(x):
    return x*x*x

print cube(1)
print cube(2)
print cube(cube(5))
# etc... 

In Haskell I can do this:

cube x = x*x*x
main = print (cube 5)

Load it with runhaskell and it will print 125.
Or I could use ghci and manually type all functions I want to test

But what I want is to use my text editor , write a couple of functions , a few tests , and have Haskell print back some results:

-- Compile this part
cube x = x*x*x

-- evaluate this part:
cube 1
cube 2
cube (cube 3)
--etc.. 

Is something like this possible?

like image 659
andsoa Avatar asked Mar 18 '13 17:03

andsoa


3 Answers

Very possible!

$ ghci
> :l filename.hs

That will load the file, and then you can use the functions directly.

> :r

That will cause the file to be reloaded after you make an edit. No need to mention the file, it will reload whatever the last one you loaded was. This also will work if you do ghci filename.hs initially instead of :l.

like image 182
Daniel Lyons Avatar answered Oct 16 '22 19:10

Daniel Lyons


cube x = x*x*x

main = do
    print $ cube 1
    print $ cube 2
    print $ cube (cube 3)
$ ghci cube.hs
...
ghci> main

See the GHCI user guide.


I also highly recommend checking out the QuickCheck library.

You'll be amazed at how awesome testing can be with it.

like image 26
ulidtko Avatar answered Oct 16 '22 20:10

ulidtko


To load a Haskell source file into GHCi, use the :load command

cf Loading source file in Haskell documentation

like image 25
Stephane Rolland Avatar answered Oct 16 '22 19:10

Stephane Rolland