-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
expression.cljc
331 lines (279 loc) · 9.87 KB
/
expression.cljc
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
;
; Copyright © 2017 Colin Smith.
; This work is based on the Scmutils system of MIT/GNU Scheme:
; Copyright © 2002 Massachusetts Institute of Technology
;
; This is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 3 of the License, or (at
; your option) any later version.
;
; This software is distributed in the hope that it will be useful, but
; WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
; General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this code; if not, see <http://www.gnu.org/licenses/>.
;
(ns sicmutils.expression
"This namespace contains a number of functions and utilities for manipulating
and comparing raw symbolic expression trees.
Also included is an implementation of a [[Literal]] type that forms the basis
for [[sicmutils.abstract.number/literal-number]]."
(:refer-clojure :rename {compare core-compare
sort core-sort}
:exclude [sorted? #?@(:cljs [compare sort])])
(:require [clojure.pprint :as pp]
[clojure.walk :as w]
[sicmutils.generic :as g]
[sicmutils.util :as u]
[sicmutils.value :as v])
#?(:clj
(:import (clojure.lang IObj))))
(def ^{:doc "These keywords reference 'abstract' types that stand in for some
concrete data type in the system."}
abstract-types
#{::numeric
::vector
::abstract-down
::abstract-matrix})
;; A Literal is a container type for literal expressions, abstract structures
;; that stand in for some other type. The canonical example is a symbolic
;; expression built out of Lisp data structures.
;;
;; Currently we only support these, but this type will be able to handle the
;; other abstract structures referenced in [[abstract-types]].
(deftype Literal [type expression m]
v/Numerical
(numerical? [_] (= type ::numeric))
v/Value
(zero? [_]
(and (v/number? expression)
(v/zero? expression)))
(one? [_]
(and (v/number? expression)
(v/one? expression)))
(identity? [_]
(and (v/number? expression)
(v/one? expression)))
(zero-like [_] 0)
(one-like [_] 1)
(identity-like [_] 1)
(exact? [_]
(and (v/number? expression)
(v/exact? expression)))
(freeze [_] (v/freeze expression))
(kind [_] type)
Object
(toString [_] (pr-str expression))
#?(:cljs
(valueOf [this]
(cond (number? expression) expression
(v/number? expression) (.valueOf expression)
:else this)))
#?(:clj
(equals [a b]
(if (instance? Literal b)
(let [b ^Literal b]
(and (= type (.-type b))
(v/= expression (.-expression b))
(= m (.-m b))))
(v/= expression b))))
#?@(:clj
[IObj
(meta [_] m)
(withMeta [_ meta] (Literal. type expression meta))
Comparable
(compareTo [_ b]
(if (instance? Literal b)
(v/compare expression (.-expression ^Literal b))
(v/compare expression b)))]
:cljs
[IMeta
(-meta [_] m)
IWithMeta
(-with-meta [_ meta] (Literal. type expression meta))
IEquiv
(-equiv [a b]
(if (instance? Literal b)
(let [b ^Literal b]
(and (= type (.-type b))
(v/= expression (.-expression b))
(= m (.-m b))))
(v/= expression b)))
IComparable
(-compare [a b]
(if (instance? Literal b)
(-compare expression (.-expression ^Literal b))
(-compare expression b)))
IPrintWithWriter
(-pr-writer
[_ writer opts]
(-write writer (str expression)))]))
#?(:clj
(defmethod print-method Literal [^Literal s ^java.io.Writer w]
(.write w (.toString s))))
(defn make-literal
"Constructs a [[Literal]] instance with the supplied type and an empty metadata
map out of the literal form `expr`."
[type expr]
(->Literal type expr nil))
(defn literal-apply
"Similar to [[make-literal]], but accepts:
- some operation
- the arguments to which it applies
Similar to `clojure.core/apply`.
For example:
```clojure
(literal-apply ::numeric 'cos [1 2 3])
;;=> (cos 1 2 3)
```"
[type op args]
(make-literal type (cons op (seq args))))
(defn literal?
"Returns true if `x` is a [[Literal]] instance, false otherwise."
[x]
(instance? Literal x))
(defn abstract?
"Returns true if `x` is both a [[Literal]] and has a type specified
in [[abstract-types]], false otherwise."
[x]
(and (literal? x)
(contains? abstract-types
(.-type ^Literal x))))
(defn literal-type
"If `x` is a [[Literal]] instance, returns its type. Else, returns nil."
[x]
(when (literal? x)
(.-type ^Literal x)))
(defn fmap
"Returns a [[Literal]] generated by applying `f` to the expression part of
`e`.
[[literal-type]] and [[meta]] will return the same thing for `e` and the
return value."
[f ^Literal e]
(->Literal (.-type e)
(f (.-expression e))
(.-m e)))
(defn expression-of
"If the supplied argument is a [[Literal]] (or a symbol, interpreted elsewhere
as a numerical literal expression), returns the wrapped expression (or the
symbol).
Else, returns `expr`."
[expr]
(if (literal? expr)
(.-expression ^Literal expr)
expr))
;; ## Expression Walking
(defn variables-in
"Return the set of 'variables' (e.g. symbols) found in `expr`.
`expr` is either a symbol, a [[Literal]] instance or some sequence
representing a symbolic expression."
[expr]
(cond (symbol? expr) #{expr}
(literal? expr) (recur (expression-of expr))
:else (into #{} (filter symbol?) (flatten expr))))
(defn evaluate
"Walk the unwrapped expression `expr` in postorder, replacing symbols found
there with their values in the `sym->var` mapping, if present.
`sym->f` is used for elements in function application position (first of a
sequence)."
[expr sym->var sym->f]
(letfn [(walk [node]
(cond (symbol? node) (sym->var node node)
(sequential? node)
(let [[f-sym & args] node]
(if-let [f (sym->f f-sym)]
;; NOTE: I'm not sure why this `doall` is required.
;; Without it, we were getting heisenbugs in the rational
;; function simplifier, and `mismatched-arity` notes.
(apply f (doall
(map walk args)))
(u/illegal (str "Missing fn for symbol - " f-sym))))
:else node))]
(walk
(expression-of expr))))
(defn substitute
"Returns a form similar to `expr`, with all instances of `old` replaced by
`new`. Substitution occurs
in [postwalk](https://clojuredocs.org/clojure.walk/postwalk) order."
([expr old new]
(substitute expr {old new}))
([expr s-map]
(w/postwalk-replace s-map expr)))
(defn compare
"Comparator for expressions. The rule is that types have the following ordering:
- empty sequence is < anything (except another empty seq)
- real < symbol < string < sequence
- sequences compare element-by-element
Any types _not_ in this list compare with the other type using hashes."
[l r]
(let [lseq? (sequential? l)
rseq? (sequential? r)
rsym? (symbol? r)
rstr? (string? r)
l-empty? (and lseq? (empty? l))
r-empty? (and rseq? (empty? r))
raw-comp (delay (core-compare (hash l) (hash r)))]
(cond (and l-empty? r-empty?) 0
l-empty? -1
r-empty? 1
(v/real? l) (cond (v/real? r) (core-compare l r)
(or rsym? rstr? rseq?)
-1
:else @raw-comp)
(v/real? r) 1
(symbol? l) (cond rsym? (core-compare l r)
(or rstr? rseq?) -1
:else @raw-comp)
rsym? 1
(string? l) (cond rstr? (core-compare l r)
rseq? -1
:else @raw-comp)
rstr? 1
lseq? (if rseq?
(let [n1 (count l)
n2 (count r)]
(cond (< n1 n2) -1
(< n2 n1) 1
:else (let [head-compare (compare
(first l) (first r))]
(if (zero? head-compare)
(recur (rest l) (rest r))
head-compare))))
@raw-comp)
rseq? 1
:else @raw-comp)))
(defn sorted? [xs]
(or (not (sequential? xs))
(every? (fn [[l r]]
(<= (compare l r) 0))
(partition 2 1 xs))))
(defn sort [xs]
(if (sequential? xs)
(core-sort compare xs)
xs))
;; ## Printing
(defn expression->stream
"Renders an expression through the simplifier and onto the stream."
([expr stream]
(-> (v/freeze
(g/simplify expr))
(pp/write :stream stream)))
([expr stream options]
(let [opt-seq (->> (assoc options :stream stream)
(apply concat))
simple (v/freeze
(g/simplify expr))]
(apply pp/write simple opt-seq))))
(defn expression->string
"Returns a string representation of a frozen, simplified version of the supplied
expression `expr`."
[expr]
(pr-str
(v/freeze (g/simplify expr))))
(defn print-expression [expr]
(pp/pprint
(v/freeze (g/simplify expr))))
(def pe print-expression)