Search code examples
racketabsolute-value

Checking if a number is negative and using absolute value in Racket


I want to check if x is negative, and if it is, get the absolute value of it. Otherwise, do nothing. Here is what I've tried so far.

(when (< x 0)
  (set! x (abs x))
  )
(set! x(abs x))

Both of these gave a "contract violation. Expected: real? Given: #f"

What am I doing wrong?

EDIT: I tried this and I think I've made progress.

(cond
  [(< x 0) (set! y(abs x))]
  [else (print "input error")]
  )

The '< x 0' is having a hard time comparing 0 to a float. How do I compare floats?


Solution

  • Why not only write

    (set! x(abs x))

    ? It will work for negative and positive values.