0
votes

I am trying to create program in Scheme (DrRacket) to solve roots of quadratic equation. I have also function to solve discriminant (function D). If discriminant is >0 function root should have on the output "point pair" (is that the correct word? english is not my native language) of both roots. Else it should give #f on the output.

(define na2
  (lambda (x)
    (* x x)))

(define D
  (lambda (a b c)
    (- (na2 b) (* 4 a c))))

(define roots
  (lambda (a b c)
    ((if (> (D a b c) 0)
     (cons (/ (+ (- b) (sqrt (D a b c))) (* 2 a)) (/ (- (- b) (sqrt (D a b c))) (* 2 a)))
     #f)))

It gives me this:

> (roots 1 3 2)
>: contract violation
expected: real?
given: (-1 . -2)
argument position: 1st
other arguments...:
> 

As you can see the correct output is there, but why the error?

Edit: I corrected typo, as Parakram Majumdar helepd me, now it gives me

application: not a procedure;
expected a procedure that can be applied to arguments
given: (-1 . -2)
arguments...: [none]

Can someone please tell what am I doing wrong?

1
I've used other dialects of scheme, where the if statement would be written as follows: (if cond then else) and the condition would be (> (D a b c) 0). So overall it should be (if (> (D a b c) 0) (cons (...)) #f). Can you please confirm if that's a typo in your code? Or is this not applicable to DrRacket?Parakram Majumdar
You are right. I corrected it. Now it gives me: application: not a procedure; expected a procedure that can be applied to arguments given: (-1 . -2) arguments...: [none] Would you know what is wrong please?SheldonCopper
It's working for me (define roots (lambda (a b c) (if (> (D a b c) 0) (cons (/ (+ (- b) (sqrt (D a b c))) (* 2 a)) (/ (- (- b) (sqrt (D a b c))) (* 2 a))) #f)))dwright
Yes! Wrong brackets near if :-D Thanks a lot guys!SheldonCopper
Now you have created a duplicate of thisSylwester

1 Answers

2
votes

As discussed in the comments, the if statement should be written as follows:

(if cond then else) 

where the condition would be :

(> (D a b c) 0)

So overall it should be:

(define roots 
    (lambda (a b c) 
            (if (> (D a b c) 0) 
                (cons (/ (+ (- b) (sqrt (D a b c))) (* 2 a)) 
                      (/ (- (- b) (sqrt (D a b c))) (* 2 a))) 
                #f
)))