select function for array

Q&A's, tips, howto's
Post Reply
cameyo
Posts: 176
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

select function for array

Post by cameyo »

"select" function for array:

Code: Select all

(define (select-array arr lst-idx)
    (array (length lst-idx)
           (map (fn(x) (arr x)) lst-idx))
)
Some test:

Code: Select all

(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:

Code: Select all

;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:

Code: Select all

(time (select tlist ind) 100)
;-> 4312.832
Write a "select" function using "select-array":

Code: Select all

(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:

Code: Select all

(time (select-list tlist ind) 100)
;-> 328.041
The user-function "select-list" is faster than the primitive "select".
Where am I doing wrong?

Post Reply