Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created August 7, 2017 01:01
Show Gist options
  • Save tautologico/cdb1ae597e08192d6a32f703e3a61a83 to your computer and use it in GitHub Desktop.
Save tautologico/cdb1ae597e08192d6a32f703e3a61a83 to your computer and use it in GitHub Desktop.
Square root function using continuations
;; sqrt function using continuations
;;
;; a port from an example in the first Scheme memo (AIM-349)
;; to modern Scheme
(define sqrt
(lambda (x epsilon)
((lambda (ans looptag)
(call-with-current-continuation
(lambda (returntag)
(begin
(set! looptag (call-with-current-continuation (lambda (k) k)))
(if (< (abs (- (* ans ans) x)) epsilon)
(returntag ans)
#f)
(set! ans (/ (+ (/ x ans) ans) 2))
(looptag looptag)))))
1.0
#f)))
;; "Anyone who doesn't understand how this manages to work
;; probably should not attempt to use CATCH" (Sussman & Steele, AIM-349)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment