0

I'm trying to make the absolute value procedure and code got an error. I don't know why :/

(define (abs x)
   (cond ((> x 0) x)
       ((= x 0) 0)
       ((< x 0) (- x))))

Error message:

define-values: assignment disallowed;
 cannot change constant
  constant: abs
Flux
  • 9,805
  • 5
  • 46
  • 92
Honolulu
  • 23
  • 3

2 Answers2

0

The abs procedure is already part of the language you're using and you can't create another procedure with the same name. Simply rename it (and the implementation can be simplified a bit, by the way):

(define (myabs x)
  (cond ((>= x 0) x)
        (else (- x))))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks! +Why do we have to put brackets around -x (line3)? I've tried without, and it's not showing correct result. – Honolulu Feb 14 '20 at 09:32
  • @Jayjay We need the brackets because we're calling the `-` procedure with a single argument: `x`. If you wrote `-x` it wouldn't work, Scheme thinks `-x` is a variable name which doesn't exist, because a dash can be part of a variable name – Óscar López Feb 14 '20 at 09:36
  • @Jayjay And to add to that `-` and `abs` are variables too and they evaluate to procedure values. – Sylwester Feb 14 '20 at 22:04
0

Here is a simple solution to your question.

(define (abs x)
(if (< x 0) (* x -1) (* x 1)))

Here is the results in DrRacket:

> (abs -4)
4

> (abs 3)
3
Bosphoran
  • 21
  • 7