Skip to content

Instantly share code, notes, and snippets.

@nyuichi
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save nyuichi/e3e2bec77cb9ba09c001 to your computer and use it in GitHub Desktop.

Select an option

Save nyuichi/e3e2bec77cb9ba09c001 to your computer and use it in GitHub Desktop.
locative in scheme
(define (make-locative accessor modifier)
(cons accessor modifier))
(define (locative-ref loc)
((car loc)))
(define (locative-set! loc value)
((cdr loc) value))
(set! (setter locative-ref) locative-set!) ; srfi-17: generalized set!
; This macro used to be very long but @dico_leque improved. Thanks!
(define-syntax locative
(syntax-rules ()
((_ v)
(make-locative
(lambda () v)
(lambda (x) (set! v x)))))) ; set! is from srfi-17
;-------
; test
; Suppose we have ! reader macro for locative-ref.
;;; catch reference to variable
(define var 1)
(define varloc (locative var))
!varloc ;=> 1
(set! !varloc 4)
!varloc ;=> 4
;;; catch reference to vector element
(define v (vector 1 2 3))
(define a (locative (vector-ref v 1)))
!a ;=> 1
(set! !a 4)
!a ;=> 4
;;; `map` procedure without extra consing
(define (map f list)
(do ((x list (cdr x))
(ans '())
(ansloc (locative ans) (locative (cdr !ansloc))))
((null? x) ans)
(set! !ansloc (list (f (car x))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment