s c h e m a t i c s : c o o k b o o k

/ Cookbook.ChainedComparisons

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Chained Comparisons

Problem

We might like to use syntax to describe a sequence of "chained" comparisons like

    3 <= x < 5

which can be expressed in Scheme as:

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

However, this evaluates x twice, so if we wanted to avoid that, we can use a let.

(let ((x-val x))
  (and (<= 3 x-val) (< x-val 5)))

But perhaps we'd like a little bit of syntactic sugar to make this go down easier.

Solution

The following macro handles much of the messiness behind chained comparisons:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 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 ...))))))

Once we have this macro, we can use it like this:

> (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

Discussion

This mimics most of the behavior behind Python's chained comparison syntax (http://www.python.org/doc/ref/comparisons.html). It avoids having to evaluate a part of the chain until it has to.


Comments about this recipe

Contributors

-- DannyYoo - 03 Feb 2006

CookbookForm
TopicType: Recipe
ParentTopic:
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest