'Racket: Trying to subtract numbers, getting list

I'm currently learning Racket/Scheme for a course (I'm not sure what's the difference, actually, and I'm not sure if the course covered that). I'm trying a basic example, implementing the Newton method to find a square root of a number; however, I ran into a problem with finding the distance between two numbers.

It seems that for whatever reason, when I'm trying to apply the subtraction operator between two numbers, it returns a list instead.

 #lang racket

(define distance
    (lambda (x y) (
            (print (real? x))
            (print (real? y))
            (abs (- x y))
        )
    )
)

(define abs
    (lambda x (
        (print (list? x))
        (if (< x 0) (- x) x)
        )
    )
)

(distance 2 5)

As you can see, I've added printing of the types of variables to make sure the problem is what I think it is, and the output of all those prints is #t. So:

  • In calling distance, x and y are both real.
  • In calling abs, x is a list.
  • So, the conclusion is that (- x y) returns a list, but why?

I double-checked with the documentation and it seems I'm using the subtraction operator correctly; I've typed (- 2 5) and then (real? (- 2 5)) into the same REPL I'm using to debug my program (Dr. Racket, to be specific), and I'm getting the expected results (-3 and #t, respectively).

Is there any wizard here that can tell me what kind of sorcery is this?

Thanks in advance!



Solution 1:[1]

How about this...

(define distance
  (lambda (x y)
    (print (real? x))
    (print (real? y))
    (abs (- x y))))


(define abs
  (lambda (x)   ;; instead of (lambda x ...), we are using (lambda (x) ...) form which is more strict in binding with formals
    (print (list? x))
    (if (< x 0) (- x) x)))

Read further about various lambda forms and their binding with formals.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1