0

i need to create this procedures: my-cons, my-car, my-cdr in Scheme.

It should work like this:

(define p1 (my-cons 3 8))

(p1 #t)

3

(p1 #f)

8

(my-car p1)

3

(my-cdr p1)

8

now, I have only this:

(define my-cons

(lambda (x y)

(cons x y)

(let ((a (car (cons x y))))

 (lambda (a)
  (if (equal? a #f) y x)))))

but in this code i can't apply my-cons or my-cdr on defined p1 Can someone help me with this?

Community
  • 1
  • 1
kelly
  • 415
  • 2
  • 9
  • 24

1 Answers1

1

First, there's some extraneous code in my-cons which doesn't seem to belong here. This is enough:

(define my-cons
  (lambda (x y)
    (lambda (a)
      (if a x y))))

(Also, you don't need to compare a boolean value with #t or #f — it's usable in if as it is.)

Now you have my-cons that returns a function which returns either x or y depending on its arugment. You can use that when implementing my-car and my-cdr:

(define my-car
  (lambda (c)
    (c #t)))

(define my-cdr
  (lambda (c)
    (c #f)))
Alexey Feldgendler
  • 1,792
  • 9
  • 17
  • ohh it's nice, i thought that will be more difficult :) but what about switch procedure? I have it in this form: `(define switch (lambda p (cons (cdr p) (car p))))` – kelly Nov 26 '12 at 14:18
  • What's your question about it? – Alexey Feldgendler Nov 26 '12 at 14:19
  • If `p1` is defined using `my-cons`, then it can't be unpacked using the standard `car` and `cdr`; you must use `my-car` and `my-cdr` on it. – Alexey Feldgendler Nov 26 '12 at 14:23
  • Please post the console log of how you're trying to use it, and what error you are getting. – Alexey Feldgendler Nov 26 '12 at 14:27
  • oh sorry, the switch proc is ok, but the line after. I'm trying this: `(define p1 (my-cons 3 8)) (define p2 (switch p1)) (my-car p2)` and the error msg: application: not a procedure; expected a procedure that can be applied to arguments given: (8 . 3) arguments...: #t – kelly Nov 26 '12 at 14:36
  • Here, you're trying to unpack with `my-car` what's been packed with the ordinary `cons` inside `switch`. – Alexey Feldgendler Nov 26 '12 at 14:38