Reputation: 1709
How can I add some testing code inside my functions?
e.g. I tried to change:
peuple i =
let parcours = ...
by:
peuple i =
do putStrLn $ "entering peuple " ++ i
let parcours = ...
but I get a parse error.
EDIT
I tried with this code :
peuple :: Int -> Arbre
peuple 1 = Feuille
peuple i =
do
print ("entering peuple " ++ show i)
...
but ghc complains the method should return a "Arbre" and not an "IO" sth.
And more generally it is possible, e.g. in scala, to replace a code by a block {..;a} and in this case, the block will be evaluated as "a". Is it possible in Haskell?
Upvotes: 0
Views: 87
Reputation: 1253
Haskell is a pure language in the sense that functions in Haskell are referentially transparent. Look at the type of peuple
:
peuple :: Int -> Arbre
A user (or other code) invoking this function should expect to give the function an Int
, and get back an Arbre
. We don't expect it to do anything else. Now what you seem to want is for an effect (or effects) to occur in this function: you want to print values to the console. Where in the type signature would you be able to tell that this function performs some sort of effect? You wouldn't. That's a no-no in Haskell.
Haskell allows us to perform effects as long as referential transparency is preserved. Printing something to the console will involve the use of the IO
monad. But the IO
monad is "one way": once you have an IO a
, you can't just extract the a
and ditch the IO
container, so that the type of the function mentions nothing of the IO
monad. If you could, then you'd have written a function that performs effects but doesn't let on that it does so. So you'll have to write a function that returns an IO Arbre
if you want the function to represent a computation that returns an Arbre
, but that performs some effects like printing to the console.
I second mb21
's suggestion to check out LYAH or another intro book that explains monads, and the IO
monad in particular.
More to the point, referential transparency is the main reason that throwing print ...
into your code is not an option in Haskell. If you want to debug code, you could use the GHCI debugger. If you want to test code, maybe use a tool like QuickCheck. Or look for other tools for debugging and testing code. But spending time learning about monads is the key here.
Upvotes: 1
Reputation: 116139
peuple i =
do putStrLn $ "entering peuple " ++ i
let parcours = ...
should be
peuple i =
do putStrLn $ "entering peuple " ++ i
let parcours = ...
since indentation matters.
Upvotes: 0