0
votes

My "distFromOrigin" function seems to be working fine, but I want to be able to find which of three points is the smallest (i.e. closest to origin). You will always be given a list of three pairs. I created a function, "closestPoint" to try and do that, but I am given the following error:

*: contract violation expected: number? given: '(1 2) argument position: 1st other arguments...:

(define t3 '( (1 2) (2 3) (3 4)))

(define distFromOrigin
  (lambda (lst)
    (sqrt (+
           (* (car lst)( car lst))
           (*(cadr lst)( cadr lst))))
    )
  )

(define closestPoint
 (lambda lst
   (< ((distFromOrigin (car lst)) ((distFromOrigin (cadr lst))) ((distFromOrigin (cadr (cdr lst)))))
      )
   )
  )
1
My eyes! Protip: Never start a line a with a closing parenthesis. 99.999% of the world population will love you for it! - leppie
Even with horrible formatting, first glance shows extra parenthesis causing the problem. Here: (< ((dist ... - leppie
Thank you, I removed the extra parenthesis. For some reason, I'm still getting the same problem, though. - user2411290

1 Answers

2
votes

In Scheme parentheses applies procedures just like in C/Java x might be a variable or a procedure, but x() is defenitely a procedure and it gets called there. This sniplet:

((distFromOrigin (car lst)) ((distFromOrigin (cadr lst)))
                            ((distFromOrigin (cadr (cdr lst)))))

The first is the operator expression that is then applied with two arguments which both are expressions that are run as thunks after evaluation. The C++ or Java version would look like this:

distFromOrigin(car(lst))( distFromOrigin(cadr(lst))(), 
                          distFromOrigin(cadr(cdr(lst)))() )

Do you see it? So distFromOrigin clearly needs to return a procedure that takes either zero or two arguments. It is NOT the same as :

(< (distFromOrigin (car lst)
   (distFromOrigin (cadr lst)) 
   (distFromOrigin (cadr (cdr lst)))))

which is probably what you want. Also know that kebab-case is the idiomatic naming convention in Lisp languages so your code should have looked like this:

(define dist-from-origin
  (lambda (lst)
    (sqrt (+ (* (car lst) (car lst))
             (* (cadr lst) (cadr lst))))))

(define closest-point
  (lambda lst
    (< (dist-from-origin (car lst)
       (dist-from-origin (cadr lst)) 
       (dist-from-origin (caddr lst))))

Notice how much easier it is to read that compared to your code. Use a good editor that makes sure you have proper identation and learn how it should look. You never really count ending parentheses you just look at the indentation to understand the structure.