• Re: collect for vector

    From B. Pym@21:1/5 to Thomas A. Russ on Sat Jul 20 09:22:33 2024
    Thomas A. Russ wrote:

    (loop with x = (make array 6 :fill-pointer 0)
    for i from 0 to 10 by 2 do (vector-push i x)
    finally return x)

    Actually, the finally clause needs to be (return x) instead.

    But if you already assume you know the size of the final array, you can dispense with the fill pointer and extension and just set it directly:

    (loop with x = (make array 6)
    for val from 0 to 10 by 2
    as index upfrom 0
    do (setf (aref x index) val)
    finally return x)

    Testing in SBCL:

    * (loop with x = (make array 6)
    for val from 0 to 10 by 2
    as index upfrom 0
    do (setf (aref x index) val)
    finally return x)

    debugger invoked on a SB-INT:SIMPLE-PROGRAM-ERROR in thread
    #<THREAD "main thread" RUNNING {23EAC1B9}>:
    A compound form was expected, but RETURN found.
    current LOOP context: FINALLY RETURN X.


    Gauche Scheme

    (list->vector (iota 6 0 2))
    ===>
    #(0 2 4 6 8 10)

    Another way.

    (vector-tabulate 6 (cut * 2 <>))

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)