Trouble with this macro - macros

Embarrassingly enough, I'm having some trouble designing this macro correctly.
This is the macro as I have it written:
(defmacro construct-vertices
[xs ys]
(cons 'draw-line-strip
(map #(list vertex %1 %2) xs ys)))
It needs to take in two collections or seqs, xs and ys, and I need it to give me…
(draw-line-strip (vertex 0 1) (vertex 1 1)
(vertex 3 3) (vertex 5 6)
(vertex 7 8))
…for xs = [0 1 3 5 7] and ys = [1 1 3 6 8].
This works just fine if I give my macro plain 'n' simple vectors (e.g. [1 2 3 4] and [2 3 4 5]) but doesn't work if I give it a lazy-seq/anything that needs to be evaluated like (take 16 (iterate #(+ 0.1 %1) 0)) and (take 16 (cycle [0 -0.1 0 0.1])))).
I realize that this is because these are passed to the macro unevaluated, and so I get, for example, (vertex take take) as my first result (I do believe). Unfortunately, everything I've tried to first evaluate these and then carry out my macro-rewriting has failed/looked terribly hacky.
I'm sure I'm missing some sort of basic syntax-quote/unquote pattern here–I'd love some help/pointers!
Thanks so much.
EDIT I should mention, draw-line-strip is a macro, and vertex creates an OpenGL vertex; they are both part of the Penumbra Clojure+OpenGL library.
EDIT 2 This is for a custom graphing tool I need, and the primary motivation for creating it was to be faster than JFreeCharts and company.
EDIT 3 I suppose I should note that I do have a macro version working, it's just horrid and hacky as I mentioned above. It uses eval, as demonstrated below, but like this:
(defmacro construct-vertices
[xs ys]
(cons 'draw-line-strip
(map #(list vertex %1 %2) (eval xs) (eval ys))))
Unfortunately, I get…
error: java.lang.ClassFormatError: Invalid this class index 3171 in constant pool in class file tl/core$draw_l$fn__9357 (core.clj:14)
…when using this with a few thousand-item long list(s). This is because I'm writing far too much into the pre-compiled code, and the classfile can't handle (I suppose) that much data/code. It looks like I need to, somehow, obtain a function version of draw-line-strip, as has been suggested.
I'm still open, however, to a more elegant, less hackish, macro solution to this problem. If one exists!

I looked at the macro expansion for draw-line-strip and noticed that it just wraps the body in a binding, gl-begin, and gl-end. So you can put whatever code inside it you want.
So
(defn construct-vertices [xs ys]
(draw-line-strip
(dorun (map #(vertex %1 %2) xs ys))))
should work.

Why not something like this, using function instead of macro:
(defn construct-vertices [xs ys]
(apply draw-line-strip (map #(list vertex %1 %2) xs ys)))
That should call draw-line-strip with required args. This example is not the best fit for macros, which shouldn't be used where functions can do.
Note: I didn't try it since I don't have slime set up on this box.
EDIT: Looking again, I don't know if you want to evaluate vertex before calling draw-line-strip. In that case function will look like:
(defn construct-vertices [xs ys]
(apply draw-line-strip (map #(vertex %1 %2) xs ys)))

If you really need draw-line-strip to be a macro and you want a fully general method of doing what the question text describes and you don't care too much about a bit of a performance hit, you could use eval:
(defn construct-vertices [xs ys]
(eval `(draw-line-strip ~#(map #(list 'vertex %1 %2) xs ys))))
; ^- not sure what vertex is
; and thus whether you need this quote
Note that this is terrible style unless it is really necessary.

This looks like a typical problem with some of the macro systems in Lisp. The usual Lisp literature applies. For example On Lisp by Paul Graham (uses Common Lisp).
Usually a macro uses the source it encloses and generates new source. If a macro call is (foo bar), and the macro should generate something different based on the value of bar, then this is generally not possible, since the value of bar is generally not available for the compiler. BAR really has only a value at runtime, not when the compiler expands the macros. So one would need to generate the right code at runtime - which might be possible, but which is usually seen as bad style.
In these macro systems macros can't be applied. A typical solution looks like this (Common Lisp):
(apply (lambda (a b c)
(a-macro-with-three-args a b c))
list-of-three-elements)
It is not always possible to use above solution, though. For example when the number of arguments varies.
It's also not a good idea that DRAW-LINE-STRIP is a macro. It should better be written as a function.

Related

How to apply lambda calculus rules in Racket?

I am trying to test some of the lambda calculus functions that I wrote using Racket but not having much luck with the testcases. For example given a definition
; successor function
(define my_succ (λ (one)
(λ (two)
(λ (three)
(two ((one two) three))))))
I am trying to apply it to 1 2 3, expecting the successor of 2 to be 3 by doing
(((my_succ 1) 2) 3)
logic being that since my_succ is a function that takes one arg and passes it to another function that takes one arg which passes it to the third function that takes one arg. But I get
application: not a procedure;
expected a procedure that can be applied to arguments
given: 1
arguments.:
I tried Googling and found a lot of code for the rules, but no examples of application of these rules. How should I call the above successor function in order to test it?
You are mixing two completely different things: lambda terms and functions in Racket.
In Racket you can have anonymous functions, that can be written in the λ notation (like (λ(x) (+ x 1)) that returns the successor of an integer, so that ((λ(x) (+ x 1)) 1) returns 2),
in Pure Lambda Calculus you have only lambda terms, that are written with in a similar notation, and that can be interpreted as functions.
In the second domain, you do not have natural numbers like 0, 1, 2, ..., but you have only lambda terms, and represent numbers as such. For instance, if you use the so-called Church numerals, you represent (in technical term encode) the number 0 with the lambda term λf.λx.x, 1 with λf.λx.f x, 2 with λf.λx.f (f x) and so on.
So, the function successor (for numbers represented with this encoding) correspond to a term which, in Racket notation, is the function that you have written, but you cannot apply it to numbers like 0, 1, etc., but only to other lambda expressions, that is you could write something like this:
(define zero (λ(f) (λ (x) x))) ; this correspond to λf.λx.x
(successor zero)
The result in Racket is a procedure (it will be printed as: #<procedure>), but if you try to test that your result is correct, comparing it with the functional encoding of 1, you will find something strange. In fact:
(equal? (successor zero) (λ(f) (λ(x) (f x))))
produces #f, since if you compare two procedures in Racket you obtain always false (e.g. (equal? (λ(x)x) (λ(x)x)) produces #f), unless you compare the “identical” (in the sense of “same memory cell”) value ((equal? zero zero) gives #t). This is due to the fact that, for comparing correctly two functions, you should compare infinite sets of couples (input, output)!
Another possibility would be representing lambda terms as some kind of structure in Racket, so you can represent Church numerals, as well as "normal" lambda terms, and define a function apply (or better reduce) the perform lambda-reduction.
You are trying to apply currying.
(define my_succ
(lambda(x)(
lambda(y)(
lambda(z)(
(f x y z)))))
(define (add x y z)
(+ x y z))
((( (my_succ add)1)2)3)
Implementation in DR Racket:

Clojure macro that doesn't need space next to it

Trying to create a macro form of Haskell's lambda syntax, I'm pretty close except one last tweak, the / (which should be a \, but can't grumble..) needs a space next to it, is there any way to make it so my macro doesn't need space between it and it's first argument?
for instance:
(reduce (/x y -> x y) [1 2 3])
instead of:
(reduce (/ x y -> x y) [1 2 3])
I suspect this isn't possible, but only way to know for sure is to ask people who know, so what's the word?
No. Macros cannot change the lexical syntax of the language. That requires read-macros, which Clojure doesn't have.
No, but if you wanted to do something more ambitious, you could define another macro with-haskell-lambdas that you wrap your entire namespace in. That macro could look through all the forms under it, eg with tree-seq, find symbols of the form /x, and replace them with / x instead.

Treat Clojure macro as a function

How can I cause a Clojure macro to act as a function, so I can pass it as an argument for example? I would expect to have to wrap it somehow.
I would not expect the wrapped version to behave exactly the same as the original macro (differences of call by name vs call by value), but it would be useful in a few cases where this wasn't important.
If I'm understanding you correctly, you can just wrap it in a function.
Consider this (silly) implementation of a squaring function as a macro:
(defmacro square [x]
(list * x x))
Passing it directly as an arg won't work, as you know:
user=> (map square [1 2 3 4 5])
java.lang.Exception: Can't take value of a macro: #'user/square (NO_SOURCE_FILE:8)
But wrapping it in a function will do the trick:
user=> (map #(square %) [1 2 3 4 5])
(1 4 9 16 25)
Alternatively (and quite a bit more evil-ly), you could make another macro to do a more generic wrapping:
(defmacro make-fn [m]
`(fn [& args#]
(eval `(~'~m ~#args#))))
user=> (map (make-fn square) [1 2 3 4 5])
(1 4 9 16 25)
I'd stick with the normal function wrapping, and skip this last hack! :)
There is a dangerous, deprecated macro that you should not ever use. :-P
http://clojure.github.com/clojure-contrib/apply-macro-api.html
For the crazy macro make-fn, how about the one below?
It should work as well, and hopefully easier to understand.
(defmacro make-fn [m]
`(fn [& args#]
(eval
(cons '~m args#))))

Why does let require a vector?

I never really thought about this until I was explaining some clojure code to a coworker who wasn't familiar with clojure. I was explaining let to him when he asked why you use a vector to declare the bindings rather than a list. I didn't really have an answer for him. But the language does restrict you from using lists:
=> (let (x 1) x)
java.lang.IllegalArgumentException: let requires a vector for its binding (NO_SOURCE_FILE:0)
Why exactly is this?
Mostly readability, I imagine. Whenever bindings are needed in Clojure, a vector is pretty consistently used. A lot of people agree that vectors for bindings make things flow better, and make it easier to discern what the bindings are and what the running code is.
Just for fun:
user=> (defmacro list-let [bindings & body] `(let ~(vec bindings) ~#body))
#'user/list-let
user=> (macroexpand-1 '(list-let (x 0) (println x)))
(clojure.core/let [x 0] (println x))
user=> (list-let (x 0 y 1) (println x y))
0 1
nil
This is an idiom from Scheme. In many Scheme implementations, square brackets can be used interchangeably with round parentheses in list literals. In those Scheme implementations, square brackets are often used to distinguish parameter lists, argument lists and bindings from S-expressions or data lists.
In Clojure, parentheses and brackets mean different things, but they are used the same way in binding declarations.
Clojure tries very hard to be consistent. There is no technical reason with a list form could not have been used in let, fn, with-open, etc... In fact, you can create your own my-let easily enough that uses one instead. However, aside from standing out visibly, the vector is used consistently across forms to mean "here are some bindings". You should strive to uphold that ideal in your own code.
my guess is that it's a convention
fn used it, defn used it, loop uses.
it seems that it's for everything that resembles a block of code that has some parameters; more specific, the square brackets are for marking those parameters
other forms for blocks of code don't use it, like if or do. they don't have any parameters
Another way to think about this is that let is simply derived from lambda. These two expressions are equivalent:
((fn [y] (+ y 42)) 10)
(let [y 10] (+ 42 y))
So as an academic or instructional point, you could even write your own very rudimentary version of let that took a list as well as a vector:
(defmacro my-let [x body]
(list (list `fn[(first x)]
`~body)
(last x)))
(my-let (z 42) (* z z))
although there would be no practical reason to do this.

extract/slice/reorder lists in (emacs) lisp?

In python, you might do something like
i = (0, 3, 2)
x = [x+1 for x in range(0,5)]
operator.itemgetter(*i)(x)
to get (1, 4, 3).
In (emacs) lisp, I wrote this function called extract which does something similar,
(defun extract (elems seq)
(mapcar (lambda (x) (nth x seq)) elems))
(extract '(0 3 2) (number-sequence 1 5))
but I feel like there should be something built in? All I know is first, last, rest, nth, car, cdr... What's the way to go? ~ Thanks in advance ~
If your problem is the speed then use (vector 1 2 3 4 5) instead of a list, and (aref vec index) to get the element.
(defun extract (elems seq)
(let ((av (vconcat seq)))
(mapcar (lambda (x) (aref av x)) elems)))
If you're going to extract from the same sequence many times of course it make sense to store the sequence in a vector just once.
Python lists are indeed one-dimensional arrays, the equivalent in LISP are vectors.
I've only done simple scripting in elisp, but it's a relatively small language. And extract is a very inefficient function on linked lists, which is the default data structure in emacs lisp. So it's unlikely to be built-in.
Your solution is the best straightforward one. It's n^2, but to make it faster requires a lot more code.
Below is a guess at how it might work, but it might also be totally off base:
sort elems (n log n)
create a map that maps elements in sorted elem to their indices in original elem (probably n log n, maybe n)
iterate through seq and sorted elem. Keep only the indices in sorted elem (probably n, maybe n log n, depending on whether it's a hash map or a tree map)
sort the result by the values of the elem mapping (n log n)
From My Lisp Experiences and the Development of GNU Emacs:
There were people in those days, in 1985, who had one-megabyte machines without virtual memory. They wanted to be able to use GNU Emacs. This meant I had to keep the program as small as possible.
For instance, at the time the only looping construct was ‘while’, which was extremely simple. There was no way to break out of the ‘while’ statement, you just had to do a catch and a throw, or test a variable that ran the loop. That shows how far I was pushing to keep things small. We didn't have ‘caar’ and ‘cadr’ and so on; “squeeze out everything possible” was the spirit of GNU Emacs, the spirit of Emacs Lisp, from the beginning.
Obviously, machines are bigger now, and we don't do it that way anymore. We put in ‘caar’ and ‘cadr’ and so on, and we might put in another looping construct one of these days.
So my guess is, if you don't see it, it's not there.