Skip to content

Instantly share code, notes, and snippets.

@DarinM223
Last active November 26, 2019 00:23
Show Gist options
  • Save DarinM223/079fddd77138a731c40dd01d392b7df7 to your computer and use it in GitHub Desktop.
Save DarinM223/079fddd77138a731c40dd01d392b7df7 to your computer and use it in GitHub Desktop.
More convenient getting/setting of multidimensional vectors in Racket
(require syntax/parse/define
(for-syntax racket/base racket/syntax))
(define-syntax-parser v!
#:datum-literals (:=)
[(_ vec:id [e:expr ...]) #'(~> vec (vector-ref e) ...)]
[(_ vec:id [e:expr ...] := exp:expr)
(define es (syntax-e #'(e ...)))
#`(~> vec
#,@(for/list ([i (in-range 0 (length es))]
[e (in-list es)])
(if (= i (- (length es) 1))
#`(vector-set! #,(syntax-e e) exp)
#`(vector-ref #,(syntax-e e)))))])
(define vec #(#(1 2 3) #(2 3 4) #(3 4 5)))
(v! vec [0 2]) ; => 3
(define vec2 (for/vector ([i (in-range 4)])
(make-vector 4 0)))
(v! vec2 [2 2] := 10)
(v! vec2 [0 0] := (+ (v! vec2 [0 0]) 1))
vec2 ; => '#(#(1 0 0 0) #(0 0 0 0) #(0 0 10 0) #(0 0 0 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment