A custom push-assoc

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

A custom push-assoc

Post by ghfischer »

During the assoc discussion I came across a problem I'm sure I knew how to solve a year or two ago, but I can't figure out anymore.

I know I'll only have assoc lists of the form

Code: Select all

((a (1 2)) (b (3 4)) ...)
I want to write a function like

Code: Select all

(push-assoc key value assoc-lst)
The only way I could get it to work is if I instead had a global assoc-lst that I used.

Code: Select all

(set 'alst '())
(define (push-assoc k v )
  (if (lookup k alst)
    (assoc-set (alst k) (list k (append (last $0) (list v))))
    (push (list k (list v)) alst -1)))
Any suggestions on how to make this so I can pass in the assoc-lst ?
I tried using a define-macro but failed.
I think I'm just missing something obvious.

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

Since 9.3.10 (load down the latest development release 9.3.11) you can pass by reference to any function using the default functor expressed as a context.

Code: Select all

; package data in a default functor
(set 'alst:alst '())

(define (push-assoc key value A)
	(push (list key value) A))
no you can pass alst:alst by reference just using the namespace identifier:

Code: Select all

> (push-assoc 'a 1 alst)
(a 1)
> (push-assoc 'b 2 alst)
(b 2)
> alst:alst
((b 2) (a 1))
> 
on 9.3.0 this would only work on functions of this form: (... (L idx) ...), now it works on any function taking a list or string.

ps: you can just take your function and add the additional parameter, and it will work this way

Locked