Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append to an alist in scheme?

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?

like image 311
troelskn Avatar asked Sep 18 '08 19:09

troelskn


People also ask

Can you append to a list in C?

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.

How does list work in Scheme?

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 () .

What does cons do in Scheme?

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.

How do I use Start Scheme?

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.


1 Answers

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:

  1. As searches are usually performed from front to back, recently added associations take precedence over older ones. This can be used for a naive implementation of both lexical and dynamic environments.
  2. While consing onto a list is O(1), appending is generally O(n) where n is the length of the list, so the idiomatic usage is best for performance as well as being stylistically preferable.
like image 89
Matthias Benkard Avatar answered Oct 20 '22 00:10

Matthias Benkard