Rahul R Badenkal
Rahul R Badenkal

Reputation: 81

How to represent the following data structure in scheme r5rs

In Python the data structure looks like this: [([1 2 3], [8 9 10])] (a list of tuple, where tuple is of size 2, and each tuple element is a list again)

How would I represent the same in Scheme r5rs?

This is what I tried: (list (cons `(1 2 3) `(8 9 10)))

But running (display (list (cons `(1 2 3) `(8 9 10)))) gives (((1 2 3) 8 9 10)) whereas I want (((1 2 3) (8 9 10)))

Edit
Using only lists (as per @Will Ness answer here):

  (list             ; a pair of elements, 
    (list 1 2 3)      ; 1      each is itself
    (list 8 9 10)))   ; 2        a list 

works.
And I can access the 2nd element of the tuple by (cadr (car x)) which gives (8 9 10) (which is correct)

I was just thinking how would I build this up using cons since my tuple will only contain 2 elements and from what I know cons are used to represent a pair in Scheme. Any ideas on how to do this using cons?

Upvotes: 1

Views: 156

Answers (2)

alinsoar
alinsoar

Reputation: 15793

There is an infinity of ways to represent data. You have been presented a way. Here is other way:

(define mk/data
  (lambda (a b)
    (lambda (?)
      (cond ((eq? ? 'repr) (list (list a b)))
            ((eq? ? 'first) a)
            ((eq? ? 'second) b)))))

(define data/test (mk/data '(1 2 3) '(8 9 10)))

(data/test 'repr)
(data/test 'first)
(data/test 'second)

This is another way how the big systems actually represent data.

Upvotes: 1

Will Ness
Will Ness

Reputation: 71075

[([1 2 3], [8 9 10])] (a list of tuple, where tuple is of size 2, and each tuple element is a list again)

(list              ; a list of
  (list             ; a pair of elements, 
    (list 1 2 3)      ; 1      each is itself
    (list 8 9 10)))   ; 2        a list 

Scheme is untyped, so we can just use lists for tuples. It is simpler that way -- the access is uniform. The first is car, the second cadr.

Your way is correct as well. What really determines whether it is or not is how you can access your data to retrieve its constituents back. And with your way you can indeed, too: the first element will be car and the second -- cdr.

(update to the question edit:) whether you use (cons 1 (cons 2 '())) or (list 1 2) is immaterial. the resulting structure in memory is the same.

Upvotes: 1

Related Questions