KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
All examples are taken from the SICP Book: http://sicpinclojure.com/?q=sicp/1-3-3-procedures-general-methods This was motivated from the MIT video series on LISP - http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-001-structure-and-interpretation-of-computer-programs-spring-2005/video-lectures/2a-higher-order-procedures/ In scheme, you can put 'define' inside another 'define': (define (close-enough? v1 v2) (define tolerance 0.00001) (< (abs (- v1 v2)) tolerance ) ) In clojure, there is the 'let' statement with the only difference that it is nested: (defn close-enough? [v1 v2] (let [tolerance 0.00001] (< (Math/abs (- v1 v2) ) tolerance) ) ) But what about rewriting in clojure something bigger like this?: (define (sqrt x) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (define tolerance 0.00001) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (fixed-point (lambda (y) (average y (/ x y))) 1.0)) This does in fact work but looks very unconventional... (defn sqrt [n] (let [precision 10e-6 abs #(if (< % 0) (- %) %) close-enough? #(-> (- %1 %2) abs (< precision)) averaged-func #(/ (+ (/ n %) %) 2) fixed-point (fn [f start] (loop [old start new (f start)]
Tags (comma-separated)
Save Edits
Cancel