logoalt Hacker News

setoptlast Tuesday at 1:15 PM2 repliesview on HN

I think also a lot of my objections could be worked around if one simply had a "math" macro that evaluates infix math notation as a DSL, similarly to how the CL "loop" macro does a DSL for iteration.

Perhaps this exists already somewhere?


Replies

veqqlast Tuesday at 5:44 PM

> exists already

The helloworld of macros lets you do `(infix 1 + 2)`:

    (defmacro infix [a op b]
      ~(,op ,a ,b))
A useful one with precedence letting you to `(infix 2 + 4 * 5)`:

    (defmacro infix  [& toks]
      (def prec {'+ 1 '- 1 '* 2 '/ 2 '% 2})
      (var pos 0)
      (defn climb [min-p]
        (var left (toks pos))
        (++ pos)
        (while (>= (get prec (get toks pos) -1) min-p) # nil/operand -> -1, stops the loop
          (def op (toks pos))
          (++ pos)
          (set left ~(,op ,left ,(climb (inc (prec op)))))) # inc => left-associative
        left)
      (climb 0))
But ultimately, APL notation is best: https://git.sr.ht/~subsetpark/jnj
xigoilast Tuesday at 7:47 PM

> Perhaps this exists already somewhere?

https://janet-lang.org/spork/api/infix.html