Trung Bún
Trung Bún

Reputation: 1147

Procedure printf in Scheme

For example, when I use the procedure printf on the list '((2 t r d)), the last line in my output is

'(#<void>)

and the number of times '(#<void>) appears depend on the number of list nested. Can you please explain this for me???

This is my printf function

(define counting 
  (lambda (lst)
    (if (null? lst)
        '()
        (printf "~a, ~s\n" (car lst) (length (cdr lst))))))

I have try to other procedure like fprintf and using this form

(fprintf (current-output-port) "~a, ~s\n" (car lst) (length (cdr lst)))

Same thing happens!

Upvotes: 2

Views: 5985

Answers (2)

GoZoner
GoZoner

Reputation: 70135

You said that 'the last line of your output is '(#<void>) - this is occurring because your Scheme environment is displaying 1) what you want to be printed and 2) the returned value of the evaluated expression. For example

> (list (display 1))
1(#<void>)

The '1' is printed and then the list result is printed. Since you are typing in an interactive session you will always get the returned value displayed. You can't really hide the returned value however most Schemes will recognize a 'undefined' return value and not print it.

> (display 1)
1

In the above, even though display returns #<void> the interpreter knows not to show it.

Upvotes: 0

Sylwester
Sylwester

Reputation: 48745

AFAIK there is no such procedure in the Scheme standard so you might need to add a tag for a implementation that has it. I know racket has printf.

A (display x) (and (printf x) in racket) alone usually don't display so what produced (#<void>) is not in the question. In Scheme every procedure evaluates to a value. To illustrate this try doing:

(map display '(1 2 3 4))

Which will return a list with 4 unspecified values since map makes a list of the results. display (and printf in racket) prints the result of the evaluation of the argument but doesn't need to return anything since the standard doesn't say that is should. Most implementations do this by returning an undefined object, but some actually return the argument too. The main function of them is to do side effect of displaying something on screen and that it has done. for ignoring return values you can use for-each which is map just for side effects.

(for-each display '(1 2 3 4))

When that said in Scheme it's normal that every procedure return something and you misread output with the REPLs printing of the returned values.

Upvotes: 1

Related Questions