Last active
November 29, 2017 11:46
-
-
Save iddm/f1b1520f93212a3b8332a9aba4229fd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang typed/racket | |
(require racket/cmdline) | |
(: square (-> Real Real)) | |
(define (square x) | |
(* x x)) | |
(: sqrt (-> Real Real)) | |
(define (sqrt x) | |
(: good-enough? (-> Real Boolean)) | |
(define (good-enough? guess) | |
(< (abs (- (square guess) x)) 0.001)) | |
(: average (-> Real Real Real)) | |
(define (average x y) | |
(/ (+ x y) 2)) | |
(: improve (-> Real Real)) | |
(define (improve guess) | |
(average guess (/ x guess))) | |
(: sqrt-iter (-> Real Real)) | |
(define (sqrt-iter guess) | |
(if (good-enough? guess) guess | |
(sqrt-iter (improve guess)))) | |
(if (< x 0) 0 (sqrt-iter 1))) | |
(: discriminant (-> Real Real Real Real)) | |
(define (discriminant a b c) | |
(- (square b) (* 4 a c))) | |
(: discriminant-solutions (-> Real Real Real (Listof Real))) | |
(define (discriminant-solutions a b c) | |
(let ((discriminant-result (discriminant a b c))) | |
(if (negative? discriminant-result) | |
(list ) | |
(let ((discriminant-result-root (sqrt discriminant-result)) | |
(double-a (* 2 a))) | |
(list (/ (- (- b) discriminant-result-root) double-a) | |
(/ (+ (- b) discriminant-result-root) double-a)))))) | |
;; (sqrt 25.0) | |
;; 2 solutions: | |
(discriminant-solutions 2.0 4.0 -7.0) | |
;; 1 solution: | |
(discriminant-solutions 1.0 6.0 9.0) | |
;; incorrect (no solutions) | |
(discriminant-solutions 2.0 4.0 7.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment