Karim Kabbara
Karim Kabbara

Reputation: 15

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?

Upvotes: 0

Views: 443

Answers (1)

Christoph S.
Christoph S.

Reputation: 603

Why not only write

(set! x(abs x))

? It will work for negative and positive values.

Upvotes: 1

Related Questions