Carp/core/Macros.carp
2017-10-18 22:44:15 +02:00

71 lines
1.8 KiB
Plaintext

(defdynamic cond-internal [xs]
(if (= (count xs) 0)
(list)
(if (= (count xs) 2)
(list)
(if (= (count xs) 1)
(car xs)
(list
'if
(car xs)
(car (cdr xs))
(cond-internal (cdr (cdr xs))))))))
(defmacro cond [:rest xs]
(cond-internal xs))
(defmacro for [settings body] ;; settings = variable, from, to, <step>
(list
'let
(array (car settings) (car (cdr settings)))
(list
'while
(list 'Int.< (car settings) (car (cdr (cdr settings))))
(list 'do
body
(list
'set! (list 'ref (car settings))
(list 'Int.+
(car settings)
(if (= 4 (count settings)) ;; optional arg for step
(car (cdr (cdr (cdr settings))))
1)))))))
(defmacro refstr [x]
(list 'ref
(list 'str x)))
(defmacro foreach [f xs]
(list 'for ['i 0 (list 'count (list 'ref xs))]
(list f (list 'nth (list 'ref xs) 'i))))
(defdynamic thread-first-internal [xs]
(if (= (count xs) 2)
(if (list? (last xs))
(cons (car (car (cdr xs)))
(cons (car xs)
(cdr (car (cdr xs)))))
(list (car (cdr xs)) (car xs)))
(if (list? (last xs))
(append
(list
(car (last xs))
(thread-first-internal (init xs)))
(cdr (last xs)))
(list (last xs) (thread-first-internal (init xs))))))
(defdynamic thread-last-internal [xs]
(if (= (count xs) 2)
(if (list? (last xs))
(cons-last (car xs) (last xs))
(list (car (cdr xs)) (car xs)))
(if (list? (last xs))
(cons-last (thread-last-internal (init xs)) (last xs))
(list (last xs) (thread-last-internal (init xs))))))
(defmacro => [:rest forms]
(thread-first-internal forms))
(defmacro ==> [:rest forms]
(thread-last-internal forms))