andsoa
andsoa

Reputation: 500

How to load a script to ghci?

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?

Upvotes: 9

Views: 13448

Answers (3)

ulidtko
ulidtko

Reputation: 15644

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.

Upvotes: 8

Stephane Rolland
Stephane Rolland

Reputation: 39926

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

cf Loading source file in Haskell documentation

Upvotes: 4

Daniel Lyons
Daniel Lyons

Reputation: 22803

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.

Upvotes: 14

Related Questions