开发者

getting an interval of a vector

I want to take an interval of a vector in Schem开发者_运维问答e. I know there is a procedure named vector->values, but seems like it returns each element separately, while I want to get the result as a vector. How can I achieve this?

> (vector->values (vector 1 2 3 4 5) 0 3)
1
2
3

while I need:

#(1 2 3)


If you're using PLT, you have a few easy ways to get this:

(define (subvector v start end)
  (list->vector (for/list ([i (in-vector v start end)]) i)))

(define (subvector v start end)
  (build-vector (- end start) (lambda (i) (vector-ref v (+ i start)))))

(define (subvector v start end)
  (define new (make-vector (- end start)))
  (vector-copy! new 0 v start end)
  new)

The last one is probably going to be the fastest. The reason that there is no such operation that is built-in is that people usually don't do that. When you're dealing with vectors in Scheme, you're usually doing so because you want to optimize something so returning a vector and a range instead of allocating a new one is more common.

(And if you think that this is useful, please suggest it on the PLT mailing list.)


The Scheme R6RS standard has make-vector, vector-ref, vector-set! and vector-length. With that you can write your own function subvector, which does not seem to be part of R6RS (!). Some Scheme implementation have something like subvector already.

You can also switch to Common Lisp, which provides the function SUBSEQ in the standard.


Here is a portable R6RS version using SRFI 43:

#!r6rs

(import (rnrs base)
        (prefix (srfi :43) srfi/43:))

(srfi/43:vector-copy (vector 1 2 3 4 5) 0 3)


#lang scheme
(define (my-vector-value v l h c)
  (if (and (>= c l) (< c h))
      (cons (first v) (my-vector-value (rest v) l h (add1 c)))
      empty))

(list->vector (my-vector-value (vector->list (vector 1 2 3 4 5)) 0 3 0))

Ghetto? Yes, very. But it only took two minutes to write and gets the job done.

(I find it's generally easier to play with lists in Scheme)


you want subvector:

(subvector (vector 1 2 3 4 5) 0 3)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜