From: Ramakrishnan Muthukrishnan <vu3rdd@gmail.com>
Date: Sun, 19 Sep 2010 18:45:46 +0000 (+0530)
Subject: some misc utilities
X-Git-Url: https://git.rkrishnan.org/%5B/using.html?a=commitdiff_plain;h=6256e3d6aa85a9758382f8ee1d5dc7df83fa6c75;p=sicp.git

some misc utilities
---

diff --git a/src/sicp/goodies.rkt b/src/sicp/goodies.rkt
new file mode 100644
index 0000000..49e8b25
--- /dev/null
+++ b/src/sicp/goodies.rkt
@@ -0,0 +1,17 @@
+#lang racket
+(provide distinct)
+
+(define (member? x lst)
+  (cond
+    [(empty? lst) #f]
+    [(equal? (first lst) x) #t]
+    [else (member? x (rest lst))]))
+
+(define (distinct lst)
+  (cond
+    [(empty? lst) '()]
+    [(member? (first lst) (rest lst)) (distinct (rest lst))]
+    [else (cons (first lst) 
+                (distinct (rest lst)))]))
+
+                  
\ No newline at end of file
diff --git a/src/sicp/misc.rkt b/src/sicp/misc.rkt
new file mode 100644
index 0000000..8234215
--- /dev/null
+++ b/src/sicp/misc.rkt
@@ -0,0 +1,58 @@
+#lang racket
+
+(define (map1 f list)
+  (cond
+    [(empty? list) '()]
+    [else (cons (f (first list))
+                (map1 f (rest list)))]))
+
+(define (mymap f lists)
+  (cond 
+    [(empty? (first lists)) '()]
+    [else (cons (apply f (map1 first lists))
+                (mymap f (map1 rest lists)))]))
+
+;; 2.28
+(define (fringe coll)
+  (cond
+    [(null? coll) '()]
+    [(not (pair? coll)) (list coll)]
+    [else (append (fringe (first coll))
+                  (fringe (rest coll)))]))
+
+(define (scale-tree tree factor)
+  (map (lambda (subtree)
+         (if (pair? subtree)
+             (scale-tree subtree factor)
+             (* subtree factor)))
+       tree))
+
+;; 2.30
+(define (square-tree1 tree)
+  (map (lambda (subtree)
+         (if (pair? subtree)
+             (square-tree1 subtree)
+             (* subtree subtree)))
+       tree))
+
+(define (square-tree2 tree)
+  (cond
+    [(null? tree) '()]
+    [(not (pair? tree)) (* tree tree)]
+    [else (cons (square-tree2 (car tree))
+                (square-tree2 (cdr tree)))]))
+                              
+(define (fringe1 tree)
+  (map (lambda (subtree)
+         (if (not (pair? subtree))
+             subtree
+             (fringe1 subtree)))
+       tree))
+       
+
+(define (tree-map f tree)
+  (map (lambda (subtree)
+         (if (pair? subtree)
+             (tree-map f subtree)
+             (f subtree)))
+       tree))
diff --git a/src/sicp/utils.rkt b/src/sicp/utils.rkt
new file mode 100644
index 0000000..b81f601
--- /dev/null
+++ b/src/sicp/utils.rkt
@@ -0,0 +1,16 @@
+#lang racket
+
+(define (square x) (* x x))
+
+(define (abs x)
+  (if (< x 0) (- x) x))
+
+(define (divides? a b)
+  (= (remainder b a) 0))
+
+(define (gcd a b)
+  (if (= b 0)
+    a
+    (gcd b (remainder a b))))
+
+(provide square)    
\ No newline at end of file