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?
The display function prints a value, including lists. It can only print a single argument.
Input scheme contains a set of possible inputs of a function and output schemes contain a set of possible outputs of a function. For example: function parameter, global variables, inFile pointer are members of input scheme and return variable, reference variable, outFile pointer are member of output scheme.
So, (begin (set! y (+ y 1)) y) increments the value of y and the y is evaluated, and then its new value is returned. begin is normally used when there is some side-effect.
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:
(define (factorial n) [...]) as a shorthand for (define factorial (lambda (n) [...])).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With