select function for array

Started by cameyo, October 04, 2020, 12:38:00 AM

Previous topic - Next topic

cameyo

"select" function for array:
(define (select-array arr lst-idx)
    (array (length lst-idx)
           (map (fn(x) (arr x)) lst-idx))
)

Some test:
(setq lst '(3 5 6 7 1 9))
(setq vec (array (length lst) lst))
(select-array vec '(0 1))
;-> (3 5)
(select-array vec '(0 1 -1))
;-> (3 5 9)
(select-array vec '(-1 -2 -3 0 1 2))
;-> (9 1 7 3 5 6)
(select-array vec '(3 3 3))
;-> (7 7 7)
(select-array vec '(0 1 6))
;-> ERR: array index out of bounds in function map : 6
;-> called from user function (select-array vec '(0 1 6))
(array? (select-array vec '(4 1)))
;-> true

Now test the "select" function of newLISP:
;List with 100000 elements (from 1 to 100000)
(silent (setq tlist (sequence 1 100000)))
;List with 10000 indexes (from 0 to 9999 randomized)
(silent (setq ind (randomize (sequence 0 9999))))

Timing:
(time (select tlist ind) 100)
;-> 4312.832

Write a "select" function using "select-array":
(define (select-list lst lst-idx)
  (array-list (select-array (array (length lst) lst) lst-idx)))
(setq lst '(3 5 6 7 1 9))
;-> (3 5 6 7 1 9)
(select-list lst '(0 1))
;-> (3 5)
(select-list lst '(0 1 -1))
;-> (3 5 9)
(select-list lst '(-1 -2 -3 0 1 2))
;-> (9 1 7 3 5 6)
(select-list lst '(3 3 3))
;-> (7 7 7)
(select-list lst '(0 1 6))
;-> ERR: array index out of bounds in function push : 6
;-> called from user function (select-array (array (length lst) lst) lst-idx)
;-> called from user function (select-list lst '(0 1 6))
(list? (select-list lst '(4 1)))
;-> true

Timing:
(time (select-list tlist ind) 100)
;-> 328.041

The user-function "select-list" is faster than the primitive "select".

Where am I doing wrong?