Make an iterative loop in the circuit

New to the circuit here, and I'm having trouble learning cycles. I try to make a function that takes an object and a vector, and then iterates over the vector until it finds this object. When an object is found, it will return a list containing all the elements in the vector in front of the object. My code is below. All it returns is the number of iterations of the do loop, not the list I want. If anyone could help me with the syntax, I would really appreciate it. Thank you (ideally, this would return (1 2))

(define(vector-test-iterative X Vector) (do ((i 0 (+ i 1))) (< i (vector-length Vector)) (if (eqv? X (vector-ref Vector i)) (= i (vector-length Vector)) (cons (vector-ref Vector i) (ls '()))) ls)) (vector-test-iterative '4 #(1 2 4 3 5)) 
+4
source share
2 answers

If you use Racket, then there is no need to use do , which has never been popular with insiders. There are a number of iterators out there - look for in docs and things starting with for . For example, your code comes down to

 #lang racket (define (values-before x vector) (for/list ([y (stop-before (in-vector vector) (lambda (y) (eqv? xy)))]) y)) 

(If you really want to use do , then you are missing a couple of partners around the test, and you need to add a binding for the battery.)

+4
source

A solution using a named loop. Cleaner (in my opinion!), Than the do version and should work on any R5RS scheme:

 ;; Extracts the sublist of `lst` up to `val`. ;; If `val` is not found, evaluates to an empty list. (define (upto val lst) (let loop ((res null) (lst lst)) (cond ((null? lst) null) ((eq? val (car lst)) (reverse res)) (else (loop (cons (car lst) res) (cdr lst)))))) ;; Adapts the above procedure to work with vectors. (define (vector-upto val vec) (list->vector (upto val (vector->list vec)))) ;; test (vector-upto 6 #(1 2 3 4 5)) => #0() (vector-upto 5 #(1 2 3 4 5)) => #4(1 2 3 4) (vector-upto 3 #(1 2 3 4 5)) => #2(1 2) (vector-upto 1 #(1 2 3 4 5)) => #0() 
+1
source

All Articles