pushing stuff

Q&A's, tips, howto's
Locked
tom
Posts: 168
Joined: Wed Jul 14, 2004 10:32 pm

pushing stuff

Post by tom »

howdy guys,

if I have something like,

Code: Select all

(set 'a '())
(push this a)
(push that a)
how can I do, instead,

Code: Select all

(push this that a)
I'm not getting it to work.

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

Does append work?

(set 'a (append a (list this) (list that)))

- doesn't look quite as nice ...

newdep
Posts: 2038
Joined: Mon Feb 23, 2004 7:40 pm
Location: Netherlands

Post by newdep »

(push "hello" a -1) perhpas?
-- (define? (Cornflakes))

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

You could write your own version of push -- mypush-- that would be used something like this:

Code: Select all

(mypush 1 2 3 'a)
Notice that I quote the stack (in this case 'a) to prevent it from being evaluated.

Something like this (this code doesn't work):

Code: Select all

(define (mypush)
  (let
    ( stack (last (args))
      list-of-items (butlast (args))
    )
  ;body of let
    (dolist (item list-of-items)
      (push item (eval stack)) )))
Since newLisp doesn't have the 'butlast' function (anybody got a good one?), I'll hack it together like this (this code works):

Code: Select all

(define (mypush)
  (let
    ( stack (last (args))
      list-of-items (reverse (rest (reverse (args))))
    )
  ;body of let
    (dolist (item list-of-items)
      (push item (eval stack) -1)) ))
I'm sure someone (Lutz?) will suggest improvements.

An alternate solution would use define-macro for a syntax more like the built-in 'push'.

Edit: I figured out that 'butlast' is easily defined with chop:

Code: Select all

;; butlast
;; return all but last n (default 1) elements of list / chars of string
;;
(define (butlast list-or-string n)
  (chop list-or-string (or n 1)) )

ghfischer
Posts: 14
Joined: Mon May 09, 2005 4:17 pm
Location: Austin, tX

Use map.

Post by ghfischer »

Code: Select all

> (set 'a '())
() 
> (set 'b '("this" "that"))
("this" "that") 
> (map (fn(x) (push x a)) b)
("this" "that") 
> a
("that" "this") 
This will push every element in b onto a.

Locked