18 May 2013

Fake call/values

For the programmers in the audience. Knowledge of Scheme is assumed.

(λ)

Lisping currently comes with TinyScheme. TinyScheme doesn’t support multiple return values (i.e. values and call-with-values). So, I did this...

;;; How to fake multiple return values
(define values list)
(define (call-with-values producer consumer)
  (apply consumer (producer)))

It was a bit surprising to me that it was that easy to fake.

This isn’t quite equivalent to the real values and call-with-values. e.g. Given a single argument, the real values function returns that argument, but my fake one returns a list instead. Which, in fact, broke another part of my code where I was using values as an identity function rather than for returning multiple values.

;;; The real values function
(values 5) → 5
;;; My fake values function
(values 5) → (5)

I imagine that real multiple return values can be more efficient than a list. On the other hand, it seems like a smart compiler could optimize-out the list in the fake version too.

Edit 21 May 2013: There is some interesting discussion here.

[...] Matthias Blume argued passionately against the presence of values/call-with-values in Scheme on the grounds that they add nothing to the language as a language—that is, they grant no additional expressiveness beyond what is already possible with list and apply [...]

The primary arguments in favour of values/call-with-values were that they allow implementors to optimise generated code in ways that are impossible or more difficult in the list/apply case.

No comments: