[plt-scheme] Little toy syntax for replicating chained comparisons al-la Python

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Thu Feb 2 04:41:33 EST 2006

Hi everyone,


I thought it might be cute to write a small macro to replicate the sort of
chained comparisons provided by Python: Python allows us to write
something like:

    3 < x <= 5

to express something like this in Scheme:

    (and (< 3 x) (<= x 5))

with the difference that Python's chained comparisons avoid evaluating x
twice.  (http://www.python.org/doc/ref/comparisons.html)


I see that there is something like this already in SRFI-67:

    http://srfi.schemers.org/srfi-67/srfi-67.html

but thought it might be fun to also provide a fairly direct Pythonic
syntax to do this:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; chained comparisons syntax
;; example: (chain x < y <= z) roughly translates to
;;          (and (< x y) (<= y z)), minus the duplicated
;;           evaluation.
(define-syntax chain
  (syntax-rules ()
    ((_ x) x)
    ((_ x op y) (op x y))
    ((_ x op y rest ...)
     (let ((y-val y))
       (and (op x y-val)
            (chain y-val rest ...))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


For example:

;;;;;;
> (define (between-5-6? n) (chain 5 < n < 6))
> (between-5-6? 3)
#f
> (between-5-6? 5)
#f
> (between-5-6? 5.5)
#t
> (define (id* x)
    (display x)
    (newline)
    x)
> (chain (id* 3) < (id* 4) > (id* 2))
4
3
2
#t
;;;;;;


Anyway, this fluttered in my brain while I browsed through HtDP Section 4,
and thought this might amuse others.  Would it be something that would be
accepted by the Schematics Cookbook, or is it too simple?


Best of wishes!



Posted on the users mailing list.