Just started with Scheme. I’m having problem with printing on console.
A simple list printing example:
(define factorial
(lambda (n)
(cond
((= 0 n) 1)
(#t (* n (factorial (- n 1)))))))
I want to print n, every time the function is called. I figured that I can’t do that within the same function? Do I need to call another function just so I can print?
Printing in Scheme works by calling
display(and possibly,newline).Since you want to call it sequentially before/after something else (which, in a functional (or in the case of Scheme, functional-ish) language only makes sense for the called functions side-effects), you would normally need to use
begin, which evaluates its arguments in turn and then returns the value of the last subexpression. However,lambdaimplicitly contains such abegin-expression.So in your case, it would go like this:
Two remarks:
(define (factorial n) [...])as a shorthand for(define factorial (lambda (n) [...])).factorialforbids tail call-optimization, therefore the program will use quite a bit of stack space for larger values of n. Rewriting it into a optimizable form using an accumulator is possible, though.If you only want to print
nonce, when the user calls the function, you will indeed need to write a wrapper, like this:And then rename your function to
inner-factorial.