Paul Manta
Paul Manta

Reputation: 31577

How to have a pair whose second element is a list?

I'd like to have a pair whose second element may be either a symbol or a list. For example, '(x . y) and '(x . (a b c d)) are both valid pairs in my context. If the second element is just a symbol, I can get the pair with cons, but what if it is a list?

Upvotes: 1

Views: 127

Answers (2)

daniel gratzer
daniel gratzer

Reputation: 53871

Then you still use cons The scheme printer is just better at printing those sort of pairs vs other ones. That's the only reason they look different.

> (define x '(1 2 3))
> (car (cons 0 x))
  0
> (cdr (cons 0 x))
  (1 2 3)

Scheme lists are really just defined recursively by this formula

  1. A list is a pair of datum and a list
  2. '() is a list. (Really that's totally arbitrary and could be anything, '() is just a very strong tradition)

Here's a pretty picture of it.

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223073

You can still use cons to do it.

(cons 'x '(a b c d))   ; => (x a b c d)

Upvotes: 0

Related Questions