Scheme console printing

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, lambda implicitly contains such a begin-expression.

So in your case, it would go like this:

 (lambda (n)
   (display n) (newline)
   (cond [...]))

Two remarks:

  1. You can use (define (factorial n) [...]) as a shorthand for (define factorial (lambda (n) [...])).
  2. The way you implement factorial forbids 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 n once, when the user calls the function, you will indeed need to write a wrapper, like this:

 (define (factorial n)
   (display n) (newline)
   (inner-factorial n))

And then rename your function to inner-factorial.

Leave a Comment