Skip to content

Commit bd553fb

Browse files
authored
feat: add assignment operator macros (#1320)
These macros apply an operation to the current value of a variable and then set the variable to the result of the application. They are effectively sugar for writing `(set! <var> (<op> <var> <val>))` and should be familiar to those who have programmed in imperative languages like C. In Carp, all the underlying operations these macros use are interfaces, so one can flexibly use them for more than just numeric types. Example usage: ```clojure (let-do [dial 0] ;; crank it up to 11! (while-do (dial < 12) (++ dial)) dial) ;; expanded (let-do [dial 0] ;; crank it up to 11! (while-do (dial < 12) (set! dial (inc dial))) dial) ```
1 parent 0188264 commit bd553fb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

core/Macros.carp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,31 @@ the filename and module name are the same.")
309309
(defmacro implements-all [mod :rest interfaces]
310310
(cons 'do (map (curry implement-declaration mod) interfaces)))
311311

312+
(doc ++
313+
"Sets the value of a variable to its current value incremented by one.")
314+
(defmacro ++ [var]
315+
(list 'set! var (list 'inc var)))
316+
317+
(doc --
318+
"Sets the value of a variable to its current value decremented by one.")
319+
(defmacro -- [var]
320+
(list 'set! var (list 'dec var)))
321+
322+
(doc +=
323+
"Sets the value of a variable to its current value plus `val`.")
324+
(defmacro += [var val]
325+
(list 'set! var (list '+ var val)))
326+
327+
(doc -=
328+
"Sets the value of a variable to its current value minus `val`.")
329+
(defmacro -= [var val]
330+
(list 'set! var (list '- var val)))
331+
332+
(doc *=
333+
"Sets the value of a variable to its current value multiplied by `val`.")
334+
(defmacro *= [var val]
335+
(list 'set! var (list '* var val)))
336+
312337
(defmodule Unsafe
313338
(defmodule C
314339
(defndynamic emit-c-line [append-strings args]

0 commit comments

Comments
 (0)