Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme console printing

Tags:

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?

like image 405
ercliou Avatar asked Feb 11 '12 02:02

ercliou


People also ask

What does display do in scheme?

The display function prints a value, including lists. It can only print a single argument.

What is input scheme?

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.

How do I use Start 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.


1 Answers

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.

like image 117
fnl Avatar answered Oct 07 '22 07:10

fnl