[racket] idioms for abstracting over definitions

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Tue May 8 09:23:54 EDT 2012


On May 7, 2012, at 5:41 PM, Patrick Mahoney wrote:

> #| 
> Hello all, in a quest for greater concision, I'm looking for a way to abstract over the following code containing mostly definitions. Is there an accepted practice for abstraction over definition introduction?|#
> 
> (define top-right-x 
>   (lambda (a-grid-plane a-cell)
>     
> ;;The next three definitions are what I am looking to abstract over, as they show up in many similarly defined functions.|#
>     (match-define (cell row-pos col-pos) a-cell)
>     
>     (define cell-size (grid-plane->cell-size a-grid-plane))
>     
>     (match-define (size cell-w cell-h) cell-size)
>     
>     (+ cell-w 
>        (* col-pos cell-w))))
> 
> (define top-right-y  
>   (lambda (a-grid-plane a-cell)
>     
>     (match-define (cell row-pos col-pos) a-cell)
>     
>     (define cell-size (grid-plane->cell-size a-grid-plane))
>     
>     (match-define (size cell-w cell-h) cell-size)
>     
>     (* row-pos cell-w)))
> 
> #|How should I approach this? are my options parameters, leaving as is, a with- macro? 


1. Define a higher-order function that computes these things: 

(define (vertical-horizontal body)
   (lambda (a-grid-plane a-cell) 
      ... defines ... 
      (body cell-w col-pos row-pos))) ;; you may need additional parameters

(define top-right-x (vertical-horizontal (lambda  (cell-w col-pos row-pos) (+ cell-w (* col-pos cell-w)))
...

That's the best solution. 

2. Define a macro for the entire function, not just the three auxiliaries. See 1, but perhaps less notation. 

3. If the above is only a hint at how complex your definitions may get, read up on units. Units are modules abstracted over context, i.e., bundles over definitions abstracted over other definitions, possibly mutually recursive. 

-- Matthias



Posted on the users mailing list.