Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Print while in recursion?

foo:: Int -> Int -> Int
foo z x = if (z < 100) 
             then z * foo (z+(x*z)) z
             else z

How would you print out(the integer z) an output every time it gets called from itself?Can you have function that returns an IO and Int? Do you need a secondary function?

like image 454
ArchHaskeller Avatar asked Mar 24 '12 03:03

ArchHaskeller


1 Answers

Building on @is7s's answer, a useful idiom for using Debug.Trace is to do this:

import Debug.Trace

foo:: Int -> Int -> Int
foo z x | trace ("z = " ++ show z) False = undefined
foo z x = if (z < 100) 
    then z * foo (z+(x*z)) z
    else z

Here, we have introduced a definition of foo with the trace in a guard which evaluates to False, so that it will always fall-through to the original definition. In this way, we do not perturb our function, and can turn the tracing on or off by commenting out the line.

like image 171
pat Avatar answered Sep 25 '22 21:09

pat