-
Notifications
You must be signed in to change notification settings - Fork 5
/
collect-terms.sls
103 lines (68 loc) · 2.57 KB
/
collect-terms.sls
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!r6rs
(library (mpl collect-terms)
(export collect-terms)
(import (mpl rnrs-sans)
(only (surfage s1 lists) iota)
(mpl misc)
(mpl arithmetic)
(mpl coeff-var-monomial))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax while
(syntax-rules ()
( (while test expr ...)
(let loop ()
(if test
(begin expr
...
(loop)))) )))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (hashtable-values tbl)
(call-with-values
(lambda ()
(hashtable-entries tbl))
(lambda (keys vals)
vals)))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (print . elts)
(for-each display elts))
(define (say . elts)
(for-each display elts)
(newline))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (collect-terms u S)
(cond ( (not (sum? u)) u )
( (member u S) u )
( else
(let ((N 0)
(T (make-eq-hashtable)))
(for-each
(lambda (i)
(let ((f (coeff-var-monomial (list-ref u i) S)))
(let ((j 1)
(combined #f))
(while (and (not combined)
(<= j N))
(if (equal? (list-ref f 1)
(list-ref (hashtable-ref T j '(#f #f)) 1))
(begin
(hashtable-set! T
j
(list (+ (list-ref f 0)
(list-ref (hashtable-ref T j #f)
0))
(list-ref f 1)))
(set! combined #t)))
(set! j (+ j 1)))
(if (not combined)
(begin
(hashtable-set! T (+ N 1) f)
(set! N (+ N 1)))))))
(cdr (iota (length u))))
(apply +
(map
(lambda (val)
(apply * val))
(vector->list
(hashtable-values T))))
))))
)