How to check my haskell functions

I just started with Haskell and first tried to write some tests. Basically, I want to define some function and call this function to check the behavior.

add :: Integer -> Integer -> Integer add ab = a+b -- Test my function add 2 3 

If I load this little script in Hugs98, I get the following error:

 Syntax error in declaration (unexpected `}', possibly due to bad layout) 

If I delete the last line, load the script and then type "add 2 3" in the hugs interpreter, it works just fine.

So the question is, how can I put my function calls in the same script as a function definition? I just want to download the script and be able to check if it does what I expect ... I donโ€™t want to enter them manually manually.

+4
source share
5 answers

Make a top-level definition:

 add :: Integer -> Integer -> Integer add ab = a + b test1 = add 2 3 

Then call test1 in the Hugs session.

+3
source

Others said how to solve your immediate problem, but for testing you should use QuickCheck or some other automated testing library .

 import Test.QuickCheck prop_5 = add 2 3 == 5 prop_leftIdentity n = add 0 n == n 

Then run quickCheck prop_5 and quickCheck prop_leftIdentity in a Hugs session. QuickCheck can do a lot more than that, but it will get you started.

(Here's the QuickCheck Tutorial , but it's out of date. Does anyone know the one that covers QuickCheck 2?)

+12
source

The friendliest way for beginners is probably the doctest module. Download it using the โ€œcabal install tutorial,โ€ then put your code in the โ€œAdd.hsโ€ file and run โ€œdoctest Add.hs" from the command line.

Your code should look like this: formatting is important:

 module Add where -- | add adds two numbers -- -- >>> add 2 3 -- 5 -- >>> add 5 0 -- 5 -- >>> add 0 0 -- 0 add :: Integer -> Integer -> Integer add ab = a+b 

HTH Chris

+7
source

How can I put my function calls in the same script as a function definition? I just want to download the script and be able to check if it does what I expect ... I donโ€™t want to enter them manually manually.

In short, you cannot. Wrap it in a function and call it instead. Your file serves as a valid Haskell module, and the expression "flying" is not a valid way to write it.

You seem to come from a scripting language, but don't try to consider Haskell as one of them.

+2
source

If you have ghc installed, the runhaskell command will interpret and run the main function in your file.

 add xy = x + y main = print $ add 2 3 

Then on the command line

 > runhaskell Add.hs 5 

Not sure, but the hugs probably have a similar function for the runhaskell . Or, if you upload the file to the hugs interpreter, you can simply run it by calling main .

0
source

All Articles