Adding an element to the head of an alist (Associative list) is simple enough:
> (cons '(ding . 53) '((foo . 42) (bar . 27)))
((ding . 53) (foo . 42) (bar . 27))
Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this:
> (define (alist-append alist pair) `(,@alist ,pair))
> (alist-append '((foo . 42) (bar . 27)) '(ding . 53))
'((foo . 42) (bar . 27) (ding . 53))
However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?
To append the elements of a list, use join. To add the new element to the beginning of the list, or at a particular index, use prepend or insert, respectively. Append always returns a new list, rather than modifying the input list, even if L is a MutableList.
Scheme Lists. The first argument of cons may be any Scheme object, and the second is a list; the value of (cons x xs) is a new list which contains x followed by the elements of xs . (Scheme's way of printing lists uses a shorthand which hides the final () .
In Scheme, car , cdr , and cons are the most important functions. The cons function is used to construct pairs and pairs are used to construct the lists. The car and cdr are used to access data and return accordingly first and second element from a pair.
So, (begin (set! y (+ y 1)) y) increments the value of y and the y is evaluated, and then its new value is returned. begin is normally used when there is some side-effect.
Common Lisp defines a function called ACONS for exactly this purpose, where
(acons key value alist)
is equivalent to:
(cons (cons key value) alist)
This strongly suggests that simply consing onto an alist is idiomatic. Note that this means two things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With