This commit is contained in:
2020-02-27 17:22:03 +01:00
commit fa8991082a
2 changed files with 49 additions and 0 deletions

21
README.md Normal file
View File

@@ -0,0 +1,21 @@
# infix
A sketch for an infix-to-prefix transformer in Carp (used for match).
Its based on my sketchy recollection of something Ive maybe seen in SICP,
and something I implemented years ago for zeptos standard library.
Its mostly instructional and I dont recommend you actually use it.
## Usage
After loading `infix.carp`, youll be able to use it like this:
```clojure
(infix 10 * 5 + 3 / 12 pow 2)
; will transform into (+ (* 10 5) (/ 3 (pow 12 2)))
```
<hr/>
Have fun!

28
infix.carp Normal file
View File

@@ -0,0 +1,28 @@
(defndynamic null? [l] (= (length l) 0))
(defndynamic infix-prec [op]
(if (Dynamic.or (= op '+) (= op '-)) 1
(if (= 'pow op) 3
2)))
(defndynamic infix-op [expr operators operands]
(infix-parse expr
(cdr operators)
(cons (list (car operators) (cadr operands) (car operands))
(cddr operands))))
(defndynamic infix-parse [expr operators operands]
(if (null? expr)
(if (null? operators)
(car operands)
(infix-op expr operators operands))
(if (list? (car expr))
(infix:parse (cdr expr) operators (cons (infix:parse (car expr)) operands))
(if (symbol? (car expr))
(if (Dynamic.or (null? operators)
(> (infix-prec (car expr)) (infix-prec (car operators))))
(infix-parse (cdr expr) (cons (car expr) operators) operands)
(infix-op expr operators operands))
(infix-parse (cdr expr) operators (cons (car expr) operands))))))
(defmacro infix [:rest args] (infix-parse args '() '()))