4 ms·
A lot of people have asked the same question over the years, and by now there are some good answers. For example many lisps implement SRFI 105: Curly Infix htt
by Y_Y 2y ago
A lot of people have asked the same question over the years, and by now there are some good answers.
For example many lisps implement SRFI 105: Curly Infix https://srfi.schemers.org/srfi-105/ https://srfi.schemers.org/srfi-105/ which lets you write {a * b + c / d} instead of (+ (* a b) (/ c d)).
Afaik Fennel doesn't have this, but that's fine because it has macros!
(macro infix [expr]
(let [stack []
ops {
"+" (fn [a b] (+ a b))
"-" (fn [a b] (- a b))
"*" (fn [a b] (* a b))
"/" (fn [a b] (/ a b))}]
(fn [item]
(if (number? item)
(table.insert stack item)
(let [op (get ops item)
b (table.remove stack -1)
a (table.remove stack -1)]
(table.insert stack (op a b)))))
(each [_ v (ipairs expr)]
(infix v))
(first stack)))
And now you can do:
(infix [1 + 2 * 3 - 4 / 5])
; => 5.2
- peeters 2y agoI can't quickly parse this in a way that makes 5.2 1 + (2 * 3) - (4 / 5) = 6.2 (PEMDAS) 1 + (2 * (3 - (4 / 5))) = 5.4 (greedy) (((1+2) * 3) - 4) / 5 = 0.4 (non-greedy) Was it a typo or is it using some other grouping I don't understand?
- deleted 2y ago[deleted]
- Y_Y 2y agoTypo, I should have actually run the code! That macro doesn't have any fancy operator precedence rules, but you could certainly add them.