How do I make this macro variadic in clojure? - macros

I want to make something called ds so that
(let [a 2]
(ds a))
->
"a->2"
and
(let [a 1 b 2 c 3]
(ds a b c))
->
"a->1, b->2, c->3"
And so far I've got as far as:
(defmacro ds3 [a b c]
`(clojure.string/join ", "
[(str '~a "->" ~a)
(str '~b "->" ~b)
(str '~c "->" ~c)]))
Which seems to work:
(let [ a 1 b 2 c 3]
(ds3 a b c)) ; "1->1, 2->2, 3->3"
Obviously I can define ds1 ds2 ds3 etc..., but I wondered how to make it variadic?

Here you go:
(defmacro ds [& symbols]
`(clojure.string/join ", "
~(into []
(map (fn [s] `(str ~(name s) "->" ~s)) symbols))))

Ankur's answer is probably the most practical, but he is deferring a lot of the work to runtime which could be done at macroexpansion time. It's a useful exercise, and a nice demonstration of the power macros can bring, to see how much of the work you can do at compile time:
(defmacro ds [& args]
`(str ~(str (name (first args)) "->")
~(first args)
~#(for [arg (rest args)
clause [(str ", " (name arg) "->") arg]]
clause)))
(macroexpand-1 '(ds a b c))
=> (clojure.core/str "a->" a ", b->" b ", c->" c)
This avoids building any temporary objects at runtime, and does the absolute minimum number of string concatenations.

EDIT:
Thanks to suggestions by #amalloy, here are some improved macros that don't use the 'badly wrong' eval and include some mini-tests:
(import 'java.lang.ArithmeticException)
(defmacro explain-expr
"Produce a string representation of the unevaluated expression x, concatenated to
an arrow and a string representation of the result of evaluating x, including
Exceptions should they arise."
[x]
`(str ~(str x) " ~~> "
(try ~x (catch Exception e# (str e#)))))
(println (explain-expr (* 42 42)))
(println (explain-expr (let [x 1] x)))
(println (explain-expr (/ 6 0)))
(println (let [x 1] (explain-expr x)))
(let [y 37] (println (explain-expr (let [x 19] (* x y)))))
(let [y 37] (println (explain-expr (let [y 19] (* y y)))))
(* 42 42) ~~> 1764
(let [x 1] x) ~~> 1
(/ 6 0) ~~> java.lang.ArithmeticException: Divide by zero
x ~~> 1
(let [x 19] (* x y)) ~~> 703
(let [y 19] (* y y)) ~~> 361
(defmacro explain-exprs
"Produce string representations of the unevaluated expressions xs, concatenated
to arrows and string representations of the results of evaluating each
expression, including Exceptions should they arise."
[& xs]
(into [] (map (fn [x]
`(str ~(str x) " ~~> "
(try ~x (catch Exception e# (str e#)))))
xs)))
(clojure.pprint/pprint
(let [y 37]
(explain-exprs
(* 42 42)
(let [x 19] (* x y))
(let [y 19] (* y y))
(* y y)
(/ 6 0))))
["(* 42 42) ~~> 1764"
"(let [x 19] (* x y)) ~~> 703"
"(let [y 19] (* y y)) ~~> 361"
"(* y y) ~~> 1369"
"(/ 6 0) ~~> java.lang.ArithmeticException: Divide by zero"]
(defmacro explanation-map
"Produce a hashmap from string representations of the unevaluated expressions
exprs to the results of evaluating each expression in exprs, including
Exceptions should they arise."
[& exprs]
(into {}
(map (fn [expr]
`[~(str expr)
(try ~expr (catch Exception e# (str e#)))])
exprs)))
(clojure.pprint/pprint
(let [y 37]
(explanation-map
(* 42 42)
(let [x 19] (* x y))
(let [y 19] (* y y))
(* y y)
(/ 6 0))))
{"(* 42 42)" 1764,
"(let [x 19] (* x y))" 703,
"(let [y 19] (* y y))" 361,
"(* y y)" 1369,
"(/ 6 0)" "java.lang.ArithmeticException: Divide by zero"}
DEPRECATED:
I'm leaving this in as an illustration of what not to do.
Here's a variation that will work on any kind of expression (I think)
(defmacro dump-strings-and-values
"Produces parallel vectors of printable dump strings and values. A dump string
shows an expression, unevaluated, then a funny arrow, then the value of the
expression."
[& xs]
`(apply map vector ;; transpose
(for [x# '~xs
v# [(try (eval x#) (catch Exception e# (str e#)))]]
[(str x# " ~~> " v#) v#])))
(defmacro pdump
"Print dump strings for one or more given expressions by side effect; return
the value of the last actual argument."
[& xs]
`(let [[ss# vs#]
(dump-strings-and-values ~#xs)]
(clojure.pprint/pprint ss#)
(last vs#))
Some samples:
(pdump (* 6 7))
prints ["(* 6 7) ~~> 42"] and returns 42.
(pdump (* 7 6) (/ 1 0) (into {} [[:a 1]]))
prints
["(* 7 6) ~~> 42"
"(/ 1 0) ~~> java.lang.ArithmeticException: Divide by zero"
"(into {} [[:a 1]]) ~~> {:a 1}"]
and returns {:a 1}.
EDIT:
My attempt to get rid of the outer brackets in the printed output, namely
(defmacro vdump
"Print dump strings for one or more given expressions by side effect; return
the value of the last actual argument."
[& xs]
`(let [[ss# vs#]
(dump-strings-and-values ~#xs)]
(map clojure.pprint/pprint ss#)
(last vs#)))
does NOT work, and I'm not sure why. It doesn't print output, but the macro expansion looks good. Could be an nREPL or REPL issue, but I gave in and just use the one above and don't worry about the brackets much.

Related

(Chez) Scheme macro for hiding lambdas

I would like to write a macro to create shorthand syntax for hiding more verbose lambda expressions, but I'm struggling to understand how to write macros (which I realize is an argument against using them).
Given this example:
(define alist-example
'((x 1 2 3) (y 4 5 6) (z 7 8 9)))
(define ($ alist name)
(cdr (assoc name alist)))
((lambda (a) (map (lambda (x y z) (+ x y z)) ($ a 'x) ($ a 'y) ($ a 'z))) alist-example)
((lambda (a) (map (lambda (y) (/ y (apply max ($ a 'y)))) ($ a 'y))) alist-example)
I would like to write a macro, with-alist, that would allow me to write the last two expressions similar to this:
(with-alist alist-example (+ x y z))
(with-alist alist-example (/ y (apply max y)))
Any advice or suggestions?
Here is a syntax-rules solution based on the feedback that I received in the other answer and comments:
(define ($ alist name)
(cdr (assoc name alist)))
(define-syntax with-alist
(syntax-rules ()
[(_ alist names expr)
(let ([alist-local alist])
(apply map (lambda names expr)
(map (lambda (name) ($ alist-local name)) (quote names))))]))
Here is some example usage:
> (define alist-example
'((x 1 2 3) (y 4 5 6) (z 7 8 9)))
> (with-alist alist-example (x) (+ x 2))
(3 4 5)
> (with-alist alist-example (x y) (+ x y))
(5 7 9)
> (with-alist alist-example (x y z) (+ x y z))
(12 15 18)
This answer stops short of solving the more complicated example, (with-alist alist-example (/ y (apply max y))), in my question, but I think this is a reasonable approach for my purposes:
> (with-alist alist-example (y) (/ y (apply max ($ alist-example 'y))))
(2/3 5/6 1)
EDIT: After some additional tinkering, I arrived at a slightly different solution that I think will provide more flexibility.
My new macro, npl, expands shorthand expressions into a list of names and procedures.
(define-syntax npl
(syntax-rules ()
[(_ (names expr) ...)
(list
(list (quote names) ...)
(list (lambda names expr) ...))]))
The output of this macro is passed to a regular procedure, with-list-map, that contains most the core functionality in the with-alist macro above.
(define (with-alist-map alist names-proc-list)
(let ([names-list (car names-proc-list)]
[proc-list (cadr names-proc-list)])
(map (lambda (names proc)
(apply map proc
(map (lambda (name) ($ alist name)) names)))
names-list proc-list)))
The 3 examples of with-alist usage above can be captured in a single call to with-alist-map.
> (with-alist-map alist-example
(npl ((x) (+ x 2))
((x y) (+ x y))
((x y z) (+ x y z))))
((3 4 5) (5 7 9) (12 15 18))
The immediate problem I see is that there is no way to tell which bindings to pick. Eg. is apply one of the elements in the alist or is it a global variable? That depends. I suggest you do:
(with-alist ((x y z) '((x 1 2 3) (y 4 5 6) (z 7 8 9)))
(+ x y z))
(let ((z 10))
(with-alist ((x y) alist-example)
(+ x y z)))
And that it should translate to:
(let ((tmp '((x 1 2 3) (y 4 5 6) (z 7 8 9))))
(apply map (lambda (x y z) (+ x y z))
(map (lambda (name) ($ tmp name)) '(x y z))))
(let ((z 10))
(let ((tmp alist-example))
(apply map (lambda (x y) (+ x y z))
(map (lambda (name) ($ tmp name)) '(x y)))))
This is then straight forward to do with syntax-rules. Eg. make a pattern and write the replacement. Good luck.

Closure inside a Common Lisp Macro

In the following code how can i have the x and y variables to reflect the expressions given at macro call time?
(defmacro defrule (init-form &rest replication-patterns)
(let (rule-table)
`(destructuring-bind (p x y) ',init-form
#'(lambda (w h) (list x y)))))
When expanding a call like:
(defrule (70 (* 1/2 w) (+ h 3)))
it returns:
(DESTRUCTURING-BIND (P X Y) '(70 (* 1/2 W) (+ H 3))
#'(LAMBDA (W H) (LIST X Y)))
where the original expressions with W and H references are lost. I tried back-quoting the lambda function creation:
(defmacro defrule (init-form &rest replication-patterns)
(let (rule-table)
`(destructuring-bind (p x y) ',init-form
`#'(lambda (w h) (list ,x ,y)))))
But a same call:
(defrule (70 (* 1/2 w) (+ h 3)))
expands to:
(DESTRUCTURING-BIND
(P X Y)
'(70 (* 1/2 W) (+ H 3))
`#'(LAMBDA (W H) (LIST ,X ,Y)))
which returns a CONS:
#'(LAMBDA (W H) (LIST (* 1/2 W) (+ H 3)))
which can not be used by funcall and passed around like a function object easily. How can i return a function object with expressions i pass in as arguments for the x y part of the init-form with possible W H references being visible by the closure function?
You're getting a cons because you have the backquotes nested.
You don't need backquote around destructuring-bind, because you're destructuring at macro expansion time, and you can do the destructuring directly in the macro lambda list.
(defmacro defrule ((p x y) &rest replication-patterns)
(let (rule-table)
`#'(lambda (w h) (list ,x ,y))))
Looking at your code:
(defmacro defrule (init-form &rest replication-patterns)
(let (rule-table)
`(destructuring-bind (p x y) ',init-form
#'(lambda (w h) (list x y)))))
You want a macro, which expands into code, which then at runtime takes code and returns a closure?
That's probably not a good idea.
Keep in mind: it's the macro, which should manipulate code at macro-expansion time. At runtime, the code should be fixed. See Barmar's explanation how to improve your code.

Function composition in Scheme

I'm trying to modify the function below to compose two functions in Scheme.
(define (compose F1 F2)
(eval F1 (interaction-environment))
)
rather than
(define (compose f g)
(λ (x) (f (g x))))
But I'm not sure about how to use eval.
From your suggestion, I guess you want to use Scheme's macros / preprocessing capabilities. eval isn't meant for code transformation. Composition ∘ can be defined in Scheme as
(define (∘ f g)
(lambda (x) (f (g x))) )
or
(define-syntax ∘
(syntax-rules ()
((∘ f g)
(lambda (x) (f (g x))) )))
where the arity of expressions f and g is 1.
(define (plus-10 n) (+ n 10))
(define (minus-3 n) (- n 3))
(display
(map (∘ plus-10 minus-3)
(list 1 2 3 4) ))
The map expression at compile-time becomes
(map (lambda (x) (plus-10 (minus-3 x)))
(list 1 2 3 4) )
equal?s
(list 8 9 10 11)

Lisp - if statements various actions

This is my lisp code.
(DEFUN F (A B)
(SETF C (* 4 A))
(SETF D (* 2 (EXPT B 3)))
(SETF RES (+ C D))
(IF (AND (TYPEP A 'INTEGER) (TYPEP B 'INTEGER))
(list 'Final 'value '= res)
'(YOUR INPUTS ARE NOT NUMBERS)))
For example, (f 5 9) works well.
But (f 'w 'q) doesn't work with the following error message:
(ERROR TYPE-ERROR DATUM W EXPECTED-TYPE NUMBER FORMAT-CONTROL
~#<~s' is not of the expected type~s'~:#> FORMAT-ARGUMENTS
(W NUMBER))
Error: W' is not of the expected typeNUMBER'
I want to make if A,B is integer calculate 4A+2B^3.
Else if at least one is not an integer print error message.
I try to the code shown above.
But how can I make this error handling using if statements?
First, you should use LET or LET* to define local variables.
(defun f (a b)
(let* ((c (* 4 a)) ; You need LET* instead of LET because
(d (* 2 (expt b 3))) ; RES depends on the previous variables.
(res (+ c d)))
(if (and (typep a 'integer) (typep b 'integer))
(list 'final 'value '= res)
'(your inputs are not numbers))))
The actual problem is that you're doing the calculations before you check that the arguments are integers. You should move the calculation inside the IF.
(defun f (a b)
(if (and (integerp a) (integerp b))
(let* ((c (* 4 a))
(d (* 2 (expt b 3)))
(res (+ c d)))
(list 'final 'value '= res))
'(your inputs are not numbers)))
Returning lists like that is kind of strange. If you intend them as output for the user, you should instead print the messages and return the actual result.
(defun f (a b)
(if (and (integerp a) (integerp b))
(let ((result (+ (* 4 a)
(* 2 (expt b 3)))))
(format t "Final value = ~a~%" result)
result) ; Return RESULT or
(format t "Your inputs are not integers.~%"))) ; NIL from FORMAT.
In most cases you should signal an error if the arguments are not correct type. Printing output from a function that does the calculation is usually a bad idea.
(defun f (a b)
(check-type a integer "an integer")
(check-type b integer "an integer")
(+ (* 4 a)
(* 2 (expt b 3))))
(defun main (a b)
(handler-case
(format t "Final value = ~a~%" (f a b))
;; CHECK-TYPE signals a TYPE-ERROR if the type is not correct.
(type-error () (warn "Your inputs are not integers."))))
(main 12 1)
; Final value = 50
;=> NIL
(main 12 'x)
; WARNING: Your inputs are not integers.
;=> NIL
Common Lisp condition system also allows you to use restarts to fix errors. CHECK-TYPE establishes a restart named STORE-VALUE, which you can invoke to supply a correct value for the place. In this case it probably doesn't make sense, but you could do something like use 1 as a default.
(defun main (a b)
(handler-bind ((type-error (lambda (e)
(store-value 1 e))))
(format t "Final value = ~a~%" (f a b))))
(main 12 1)
; Final value = 50
;=> NIL
(main 12 'x)
; Final value = 50
;=> NIL
Notice that conditions/error handlers do add some overhead, so for performance critical functions you might not want to use them and instead check your arguments before calling the function.
(declaim (ftype (function (integer integer) integer) f))
(defun f (a b)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(+ (* 4 a)
(* 2 (expt b 3))))
(defun main (a b)
(if (and (integerp a)
(integerp b))
(format t "Final value = ~a~%" (f a b))
(warn "Your inputs are not integers.")))

Clojure's -> and ->> macro

Clojure's ->> macro thread the form from the last argument, when -> form from the first.
user=> (->> a (+ 5) (let [a 5]))
10
However, I get an exception when I used the operations exchanged.
user=> (-> a (let [a 5]) (+ 5))
CompilerException java.lang.IllegalArgumentException: let requires a vector for its binding in user:1, compiling:(NO_SOURCE_PATH:1:7)
Furthermore, I expect these two operations will get me the same results, which is not.
user=> (-> 0 (Math/cos) (Math/sin))
0.8414709848078965
user=> (->> 0 (Math/sin) (Math/cos))
1.0
What's wrong? How's the -> and ->> macros work?
The -> macro inserts the argument as the first argument for the given function, not giving the argument to the last function.
Likewise ->> inserts as the last argument.
user=> (macroexpand '(-> x (- 1)))
(- x 1)
user=> (macroexpand '(->> x (- 1)))
(- 1 x)
Two simple examples:
user=> (-> 1 (- 1) (- 2))
-2
user=> (->> 1 (- 1) (- 2))
2
As for the first example, -2 == (- (- 1 1) 2), and for the second 2 == (- 2 (-1 1))
As a result, we get the same results for the unary functions.
user=> (macroexpand '(-> 0 Math/sin Math/cos))
(. Math cos (clojure.core/-> 0 Math/sin))
user=> (macroexpand '(->> 0 Math/sin Math/cos))
(. Math cos (clojure.core/->> 0 Math/sin))
So, only ->> makes sense in the question.
user=> (macroexpand '(->> a (+ 5) (let [a 5])))
(let* [a 5] (clojure.core/->> a (+ 5)))
user=> (macroexpand '(-> a (+ 5) (let [a 5])))
IllegalArgumentException let requires a vector for its binding in user:1 clojure.core/let (core.clj:4043)