Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else construction

I am trying to solve a basic function. but I get an error with my second if statement and the else.Ff you can give me a help here is the code.

(define (equation x)
  (if(> x 2) (+(-(* x x) x) 4) ) 
  (if (and (> x 1 ) (= x 1))  (and (< x 2) (= x 2)) (/ 1 x))
  (else 0)
  )
like image 208
Doesn't Matter Avatar asked Jul 23 '12 14:07

Doesn't Matter


3 Answers

There are several errors in your code. And you should use a cond when dealing with multiple conditions (think of it as a series of IF/ELSE IF/.../ELSE statements).

Be aware that the expression (and (> x 1) (= x 1)) will never be true, as x is either greater than or equal to 1, both conditions can never be true at the same time. You probably meant (or (> x 1) (= x 1)), but even so that expression can be written more concisely as (>= x 1). The same considerations apply for the condition (and (< x 2) (= x 2)).

I believe this is what you were aiming for:

(define (equation x)
  (cond ((> x 2)
         (+ (- (* x x) x) 4))
        ((and (>= x 1) (<= x 2))
         (/ 1 x))
        (else 0)))
like image 116
Óscar López Avatar answered Sep 30 '22 17:09

Óscar López


The format of if condition is (if (condition) (consequent) (alternate)). The else cannot be used with if. Here's the same code without using cond/else

(define (equation x)
  (if (> x 2) 
      (+ (- (* x x) x) 4)
      (if (and (or (> x 1) (= x 1)) (or (< x 2) (= x 2)))
          (/ 1 x)
          0)))

Or alternatively

(define (equation2 x)
  (if (< x 1) 
      0
      (if (> x 2)
          (+ (- (* x x) x) 4)
          (/ 1 x)))) 
like image 33
Rajesh Bhat Avatar answered Sep 30 '22 18:09

Rajesh Bhat


and (> x 1 ) (= x 1) is alwayse false

and (< x 2) (= x 2) is always false

There is no operator to connect work with the second if

like image 44
Ussr Avatar answered Sep 30 '22 17:09

Ussr