views:

72

answers:

2

Okay this is my 4th question today on Scheme, still pretty new to Scheme, as I needed for one of my sub-function I asked earlier in the day.

Basically this will return me the difference of 2 lists. Say you've got (1,5) and (5,1) this function should return me 8. As that's the distance between l to w

Here is what I have. Note: if I change the (list (- (car l) (car w))) into (write ..... ) the function will work, but outputs 2 number which I have no idea how to use those number as inputs of my other function.

So I try to put it into list, but doesn't really work out, it returns me with no error but weird stuff

(define (difference l w) ; calc heuristic function estimation
    (if (> (car l) (car w))
        (list (- (car l) (car w)))
        (if (< (car l) (car w))
        (list (- (car w) (car l)))))
        (if (< (list-ref l 1) (list-ref w 1))
            (list (- (list-ref l 1) (list-ref w 1)))
            (if (> (list-ref l 1) (list-ref w 1))
                (list (- (list-ref w 1) (list-ref l 1)))))
   )

Here is the code returned me

> (difference '(9 1) '(3 1))
#<procedure:...0\assigment 2.ss:50:3>

Any ideas? try to use lambda end-up the same thing.

+1  A: 

Well first of all, there's a typo in your code...

(lits (- (car w) (car l)))))

should be...

(list (- (car w) (car l)))))

EDIT: Would something like this work?

(define (difference lst1 lst2) 
    (if (> (car lst1) (car lst2))
        (+ (- (car lst1) (car lst2)) (difference (cdr lst1) (cdr lst2)))
        (+ (- (car lst2) (car lst1)) (difference (cdr lst1) (cdr lst2))))
)
Andrew Song
oopz i was using write instead and it works fine, but I can't use the output into any input. No use for me to use write or display function. So i try to use cons, append, list none of them is working
Jonathan
Something like that...?
Andrew Song
the weird that I didn't use cdr is because car return me a number rather cdr return me one number of a list. Yea that's why i use the list-ref to make sure I can do the calculation
Jonathan
`car` returns the 'first' element of a list, which is just a number. `cdr` returns the 'rest' of the list, which is a list of length one (think of pointers in C). `(list-ref .. N)` returns the Nth element of the list, thus `(list-ref .. 1)` is actually `(car (cdr lst))`, or abbreviated to `(cadr lst)`.If this worked for you, feel free to accept the answer.
Andrew Song
A: 

I know it's an old question, but I just wrote something like this. Here's my solution

(define (difference l1 l2)
  (apply + (map abs (map - l1 l2))))
Martin Neal