[racket] idioms for abstracting over definitions
Here's one way to do it:
(define-values (top-right-x top-right-y)
(let ()
(define (mk x?)
(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)
(if x?
(+ cell-w (* col-pos cell-w))
(* row-pos cell-w))))
(values (mk #t) (mk #f))))
You define an internal helper, `mk', that returns `top-right-x' or
`top-right-y' depending on it's input. You then use it to generate both
functions and bind them with `define-values'.
If you prefer currying:
(define-values (top-right-x top-right-y)
(let ()
(define ((mk x?) 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)
(if x?
(+ cell-w (* col-pos cell-w))
(* row-pos cell-w)))
(values (mk #t) (mk #f))))
Unfortunately, the `let' is necessary here because `define-values' only
accepts one body element.
Vincent
At Mon, 7 May 2012 17:41:12 -0400,
Patrick Mahoney wrote:
>
> [1 <multipart/alternative (7bit)>]
> [1.1 <text/plain; UTF-8 (7bit)>]
> #|
> 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?
>
> Much appreciated all,
> -Patrick
> |#
> [1.2 <text/html; UTF-8 (quoted-printable)>]
>
> [2 <text/plain; us-ascii (7bit)>]
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users