File tree Expand file tree Collapse file tree 4 files changed +91
-0
lines changed
1.1-TheElementsOfProgramming Expand file tree Collapse file tree 4 files changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ (defn p [] p )
2
+
3
+ (defn test
4
+ [x y]
5
+ (if (> x 0 ) 0 y))
6
+
7
+ (test 0 (p ))
8
+
9
+ ; The expression (test 0 (p)) will end in a infinite loop if the programming language evaluates in applicative-order
10
+ ; In normal order evaluation the expression is evaluated outside in, terminating the execution.
Original file line number Diff line number Diff line change
1
+ (defn new-if
2
+ [predicate then-clause else-clause]
3
+ (cond predicate then-clause
4
+ :else else-clause))
5
+
6
+ (defn average
7
+ [x y]
8
+ (/ (+ x y) 2 ))
9
+
10
+ (defn improve
11
+ [guess x]
12
+ (average guess (/ x guess)))
13
+
14
+ (defn square [x] (* x x))
15
+
16
+ (defn abs [n] (max n (- n)))
17
+
18
+ (defn good-enough?
19
+ [guess x]
20
+ (< (abs (- (square guess) x)) 0.001 ))
21
+
22
+ (defn sqrt [x]
23
+ (sqrt-iter 1.0 x))
24
+
25
+ (defn sqrt-iter
26
+ [guess x]
27
+ (new-if (good-enough? guess x)
28
+ guess
29
+ (sqrt-iter (improve guess x) x)))
30
+
31
+ ; clojure uses applicative-order evaluation so new-if will get evaluated
32
+ ; substituting all arguments first so sqrt-inter will end up in a infinite loop
Original file line number Diff line number Diff line change
1
+ (defn new-if
2
+ [predicate then-clause else-clause]
3
+ (cond predicate then-clause
4
+ :else else-clause))
5
+
6
+ (defn average
7
+ [x y]
8
+ (/ (+ x y) 2 ))
9
+
10
+ (defn improve
11
+ [guess x]
12
+ (average guess (/ x guess)))
13
+
14
+ (defn square [x] (* x x))
15
+
16
+ (defn abs [n] (max n (- n)))
17
+
18
+ (defn good-enough?
19
+ [guess x]
20
+ (< (abs (- (square guess) x)) 0.001 ))
21
+
22
+ (defn sqrt [x]
23
+ (sqrt-iter 1.0 x))
24
+
25
+ (defn sqrt-iter
26
+ [guess previous-guess x]
27
+ (new-if (good-enough? guess previous-guess)
28
+ guess
29
+ (sqrt-iter (improve guess x) guess x)))
Original file line number Diff line number Diff line change
1
+ (defn square [x] (* x x))
2
+ (defn cube [x] (* x x x))
3
+ (defn abs [n] (max n (- n)))
4
+
5
+ (defn improve [guess x]
6
+ (/ (+ (/ x (square guess))
7
+ (* 2 guess) )
8
+ 3 ))
9
+
10
+ (defn good-enough? [guess x]
11
+ (< (abs (- (cube guess) x)) 0.001 ))
12
+
13
+ (defn cbrt-iter [guess x]
14
+ (if (good-enough? guess x)
15
+ guess
16
+ (cbrt-iter (improve guess x) x)))
17
+
18
+ (defn cbrt [x]
19
+ (cbrt-iter 1.0 x))
20
+
You can’t perform that action at this time.
0 commit comments