Repository navigation
Expand file tree
/
Copy pathshape-geometry.sema
More file actions
64 lines (55 loc) · 1.78 KB
/
Copy pathshape-geometry.sema
File metadata and controls
64 lines (55 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
;; shape-geometry.sema — Geometric shapes using match and map destructuring
;; Demonstrates: match on map patterns, {:keys} destructuring, guards
(define (area shape)
(match shape
({:type :circle :radius r} (* pi r r))
({:type :rect :w w :h h} (* w h))
({:type :triangle :base b :height h} (/ (* b h) 2))
({:type :square :side s} (* s s))
(_ (error f"Unknown shape: ${shape}"))))
(define (perimeter shape)
(match shape
({:type :circle :radius r} (* 2 pi r))
({:type :rect :w w :h h} (* 2 (+ w h)))
({:type :triangle :a a :b b :c c} (+ a b c))
({:type :square :side s} (* 4 s))
(_ nil)))
(define (describe shape)
(let (({:keys [type]} shape))
(let ((a (/ (round (* (area shape) 100)) 100.0))
(p (perimeter shape)))
(println f" ${type}: area=${a}, perimeter=${(if p (round p) "N/A")}"))))
(define shapes
(list {:type :circle :radius 5}
{:type :rect :w 4 :h 7}
{:type :triangle :base 6 :height 3 :a 5 :b 6 :c 7}
{:type :square :side 3}))
(println "=== Shape Geometry ===\n")
(for-each
describe
shapes)
;; Scale a shape
(define (scale shape factor)
(match shape
({:type :circle :radius r} {:type :circle :radius (* r factor)})
({:type :rect :w w :h h} {:type :rect :w (* w factor) :h (* h factor)})
({:type :square :side s} {:type :square :side (* s factor)})
(other other)))
(println "\nScaled ×2:")
(->> shapes
(filter #(not (= (get % :type) :triangle)))
(map #(scale % 2))
(for-each describe))
;; Classify by area
(define (classify shape)
(let ((a (area shape)))
(match a
(a when (> a 50) "large")
(a when (> a 20) "medium")
(_ "small"))))
(println "\nClassification:")
(for-each
(fn (s)
(let (({:keys [type]} s))
(println f" ${type} → ${(classify s)}")))
shapes)