I'm trying to modify this snippet from SICP:
(define (whatever x y)
(newline)
(display "called with ")
(display x)
(if (> x y)
0 ; if x <= y, return 0 and skip the rest
(+ x (whatever (+ 1 x) y))))
What I want to do is add a line in "the rest" that prints out the value being returned before the
value is returned. For example, now my output for (whatever 1 5)
gives:
called with 1
called with 2
called with 3
called with 4
called with 5
called with 6
;Value: 15
I want it to give:
called with 1 returning 15
called with 2 returning 14
called with 3 returning 12
called with 4 returning 9
called with 5 returning 5
called with 6 returning 0
;Value: 15
Everything I try either tells me that I got the syntax wrong or says something about 'object #!unspecific
' being the wrong type. I understand why I'm getting those errors (i.e. the function wants to return a number but (display (+ x (whatever (... )))
doesn't return the right kind of value).
(define...
0
(display (+ x (whatever (+ x 1) y))))
gives an error message saying object #!unspecific
is the wrong type
If I change it to
(define...
0
(display (+ x (whatever (+ x 1) y))))
(+ x (whatever (+ x 1) y))))
gives an ill-formed syntax error that I can't get rid of after double and triple checking my parenthesis nesting.
If I take out the (display ... )
it works as expected.
Would anyone be willing to show me a lean way to get the output I want?
You can't print the result until after the recursion has returned, so if you print the argument first,
the output is:
If you want the argument and result on the same line, they end up in the other order
Output
If you want to reverse the order of that, it becomes more complicated.