[racket] idioms for abstracting over definitions
On Mon, 07 May 2012 19:43:37 -0400
users-request at racket-lang.org 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?
>
> Much appreciated all,
> -Patrick
> |#
Hi,
;;;
;;; You have specific implementations
;;; ---------------------------------
(define f1
(lambda (...)
(define a ...)
(define b ...)
...
(your-computation-1 a b ...)))
(define f2
(lambda (...)
(define a ...)
(define b ...)
...
(your-computation-2 a b ...)))
...
;;;
;;; You can refactor them to one generic and it's applications
;;; ----------------------------------------------------------
(define generic-f
(lambda (your-computation ...)
(define a ...)
(define b ...)
...
(your-computation a b ...)))
(define f1 (generic-f (lambda (a b ...) (your-computation-1 a b ...)))
(define f2 (generic-f (lambda (a b ...) (your-computation-2 a b ...)))
...
;; but it can obfuscate things not make them more clear,
;; because you'll be giving more arguments to ``your-computation''
;; than it needs. It works better when all computations
;; use same arguments
--
Nikita B. Zuev