[plt-scheme] PLT's lambda substituting for native case-lambda

From: soo (tilde at tilde.co.kr)
Date: Wed May 28 00:43:44 EDT 2008

Hi,
I'd like to suggest substituting lambda for case-lambda.

All the lambda special forms that support optional variables can
substitute for  case-lambda as follows:
In Mzscheme,

(define case-str
  (case-lambda
   ((str) (string-length str))
   ((str num) (string-ref str num))
   ((str num chr) (string-set! str num chr))))

(define cond-str
  (let ((u (lambda () #f)))    ;must be unique like (gensym) or (lambda
() #f)
    (lambda (str (num u) (chr u))
      (cond
       ((eq? u num) (string-length str))
       ((eq? u chr) (string-ref str num))
       (else (string-set! str num chr))))))

The cond-str has the same performance speed as the case-str in PLT-3.99.

In addition, the lambda special forms that support optional keyword
variables can make the equivalent of the case-lambda that
supports them, as follows:
In Mzscheme,

(define cond-str-key
  (let ((u (lambda () #f)))
    (lambda (str #:num (num u) #:chr (chr u))
      (cond
       ((and (eq? u num) (eq? u chr))
	(string-length str))
       ((eq? u chr)
	(string-ref str num))
       ((not (or (eq? u num) (eq? u chr)))
	(string-set! str num chr))))))

examples:
(define str (string #\a #\b #\c #\d #\e))

(case-str     str)
(cond-str     str)
(cond-str-key str)
=> 5

(case-str     str 1)
(cond-str     str 1)
(cond-str-key str #:num 1)
=> #\b

(case-str     str 1 #\f)
(cond-str     str 1 #\f)
(cond-str-key str #:num 1 #:chr #\f)
str => "afcde"

Thanks.
--
Joo ChurlSoo 







Posted on the users mailing list.