Racket-y way on multidimensional vectors operation?

旧城冷巷雨未停 提交于 2019-12-20 03:20:02

问题


I've read this question before, and followed Eli Barzilay's answer on srfi-25.

Besides reading the source code of srfi-25, I found writing some auxiliary function would be much more easier, for example

#lang racket

(define (set2v! vec x y value)
  (vector-set! (vector-ref vec x) y value))

(define (get2v vec x y)
  (vector-ref (vector-ref vec x) y))

(define v2 (vector (vector 1 2 3) (vector 4 5 6) (vector 7 8 9)))

(get2v v2 1 1)

(set2v! v2 1 1 99)

(get2v v2 1 1)

I was wondering if there maybe some Racket-y way on multidimensional vectors operation?


回答1:


An alternative to using nested vectors for multidimensional vectors is to use the math library's array data structure.

Here's an example use:

Welcome to Racket v6.4.0.4.
-> (require math/array)
-> (define arr (mutable-array #[#[1 2 3] #[4 5 6]]))
-> (array-ref arr #(0 0))
1
-> (array-ref arr #(1 2))
6
-> (array-set! arr #(1 2) 15)
-> (array-ref arr #(1 2))
15

There is a caveat that this will be slower when you use the library from untyped code (e.g., #lang racket). It will be fast when used in Typed Racket.



来源:https://stackoverflow.com/questions/35009590/racket-y-way-on-multidimensional-vectors-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!