0
votes

I am new to scheme, and have the following question: If I want a function to also print -the value- of an expression and then call a function, how would one come up to doing that?

For example, I need the function foo(n) to print the value of n mod 2 and call foo(n/2), I would've done:

(define foo (lambda (n) (modulo n 2) (foo (/ n 2))))

But that, of course, would not print the value of n mod 2.

4

4 Answers

1
votes

Here is something simple:

(define foo 
  (lambda (n) 
    (display (modulo n 2))
    (when (positive? n)
     (foo (/ n 2)))))

Note the check of (positive? n) to ensure that you avoid (/ 0 2) forever and ever.

0
votes

I'm terrible at Lisp, but here's an idea: Maybe you could define a function that prints a value and returns it

(define (debug x) (begin (display x) (newline) x))

Then just call the function like

(some-fun (debug (some expression)))
0
votes

As @Juho wrote, you need to add a display. But, your procedure is recursive without a base case, so it will never terminate.

Try this:

(define foo 
  (lambda (n) 
    (cond
      ((integer? n) (display (modulo n 2))
                    (newline)
                    (foo (/ n 2)))
      (else         n))))

then

> (foo 120)
0
0
0
1
7 1/2
0
votes

Usually when dealing with more than one thing it's common to build lists to present a solution when the procedure is finished.

(define (get-digits number base)
  (let loop ((nums '()) (cur number))
    (if (zero? cur)
        nums
        (loop (cons (remainder cur base) nums)
              (quotient cur base)))))

(get-digits 1234 10) ; ==> (1 2 3 4)

Now, since you use DrRacket you have a debugger so you can actually step though this code but you rather should try to make simple bits like this that is testable and that does not do side effects.

I was puzzled when you were taling about pink and blue output until I opened DrRacket and indeed there it was. Everything that is pink is from the program and everything blue is normally not outputed but since it's the result of top level forms in the IDE the REPL shows it anyway. The differences between them are really that you should not rely on blue output in production code.

As other has suggested you can have debug output with display within the code. I want to show you another way. Imagine I didn't know what to do with the elements so I give you the opportunity to do it yourself:

(define (get-digits number base glue)
  (let loop ((nums '()) (cur number))
    (if (zero? cur)
        nums
        (loop (glue (remainder cur base) nums)
              (quotient cur base)))))

(get-digits 1234 10 cons)  ; ==> (1 2 3 4)

(define (debug-glue a d)
  (display a)
  (newline)
  (cons a d))

(get-digits 1234 10 debug-glue)  ; ==> (1 2 3 4) and displays "4\n3\n2\n1\n"