1

I'm a Scheme newbie and trying to make sense of my homework. I've a function I made earlier called duplicate, and it looks like this:

( DEFINE ( duplicate lis )
          (IF (NULL? lis) '())
          ((CONS (CAR lis) (CONS (CAR lis) (duplicate (CDR lis))))
         ))

A typical i/o from this would be i: (duplicate '(1 2 3 4)) o: (1 1 2 2 3 3 4 4), so basicly it duplicates everything in the list. Moving on: Now I'm supposed to make a function that's called comp. It's supposed to be built like this:

(DEFINE (comp f g) (lambda (x) (f (g (x))))

Where I could input '(1 2 3 4) and it would return (1 1 4 4 9 9 16 16)

so f = duplicate and g = lambda. I know lambda should probably look like this:

(lambda (x) (* x x))

But here's where the problem starts, I've already spent several hours on this, and as you can see not made much progress.

Any help would be appreciated. Best regards.

1
  • 1
    1. In comp() you can't have (x); xis not a function: it should be (g x) instead of (g(x)) 2. To use comp with lambda , your (lambda(x..)) needs to work on a list to be compatible with double; as it is, this lambda only works on a single number. That is hard to do without loop. Commented Nov 15, 2010 at 14:04

2 Answers 2

2

Use map:

> (map (lambda (x) (* x x)) (duplicate '(1 2 3 4)))
=> (1 1 4 4 9 9 16 16)

or, modify duplicate to take a procedure as its second argument and apply it to each element of the list:

(define (duplicate lst p)
  (if (null? lst) ()
      (append (list (p (car lst)) (p (car lst))) (duplicate (cdr lst) p))))

> (duplicate '(1 2 3 4) (lambda (x) (* x x)))
=> (1 1 4 4 9 9 16 16)
Sign up to request clarification or add additional context in comments.

Comments

0

One way to do is as follows:

(define (comp f g) (lambda (x) (f (g x))))
(define (square x) (* x x))
(define (dup x) (list x x))
(define (duplicate-square lst)
  (foldr append '() (map (comp dup square) lst)))

Now at the repl, do:

> (duplicate-square '(1 2 3 4))
'(1 1 4 4 9 9 16 16)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.