Common Lisp Macro to T-Sql Experiment

So just another jump into the unknown, I wondered great wonders about creating a macro in Common Lisp that would just print out what I type between the () into T-Sql. Essentially, I want to type this:

(select age)

And get:

"SELECT, age"

Now there are probably a billion (or slightly less) examples of using keywords like:

(select '


(select :user name)

Or whatever.  Not good enough for me. I am more demanding.

So the first stab was something simple;  Just take an arbitrarily (I actually spelled that correctly the first time) long list of names, and create a string from it. And here it was:

(defmacro select (&rest args)
  `(mapcar #'write-to-string (list ,@args)))

Basically, take the parameter “args”, strip the () surrounding it, create a new list, and create a string from every member. A quick macroexpand show the outcome:

(macroexpand-1 '(select 'test 'me)) 
    -> ("TEST" "ME")

As shown, that is just a list of “test” and “me”. Doesn’t make the cut, mostly because I had to use “APOSTROPHEtest” instead of just “test”. Oh and there’s no string. Time to take care of that:

(defmacro select (&rest args)
  `(concatenate 'string  ,@(mapcar #'write-to-string args)))

So now it should take the list of strings ‘(“TEST” “ME”)’, and make it a nice string. DOES IT?!?!?

(macroexpand-1 '(select 'test 'me))
    -> OOPS

Go figure, it left the APOSTROPHE on the words. Actually, this is good sign. It means I don need to prefix the names with an APOSTROPHE  anymore. Next attempt:

(macroexpand-1 '(select test me))
    -> "TESTME"

Now it’s getting there. Only thing is: There needs to be a separation added. Duh, right? Might as well throw in the “SELECT” part too.

(defmacro select (&rest args)
  `(concatenate 'string "SELECT "
     ,@(mapcar #'(lambda (z) (concatenate 'string (write-to-string z) ", ")) args)))

Big change here was adding the “, ” to the converted keywords, then take the newly created partial string and make one long string.

(macroexpand-1 '(select age))

And there it is. Can’t get much better than that.

Common Lisp and Reader Macros… You Better Sit Down For This

Fair warning: I only learned about reader macros today, so my terminology may suck. Well, most likely it would still even if I had a couple weeks. So it will suck more. Say, 20% more suck.

In case you didn’t get a chance to read my primer on macros (Let’s be honest, you didn’t. It’s ok, I’ll be fine.), this next macro may not look familiar. This is the post of which I type. A quick recap is that the macro would take this:

  (?> (+ 1% 2% 3%) '(4) '(5) '(6))

And create this code:

  (MAPCAR #'(LAMBDA (1% 2% 3%) (+ 1% 2% 3%)) '(4) '(5) '(6))

Essentially it took the original expression, and created a lambda with dynamically created parameters. (The 1% 2% 3% part) The macro “keyword” if you will is the “?>
Here’s the macro minus the helper methods. (The whole thing is the last section of the same post from above.)

  (defmacro ?> (conversion &rest args)
   `(mapcar #'(lambda (,@(create-placeholders args)) (,@conversion)) ,@args))

Now that’s pretty cool and all, but it still has to follow the general rule of Common Lisp: Every statement is encased in parenthesis. After all, the macro starts with “(?>”. What if there was a way to take that and remove any need for outer parenthesis? Turns out there is, and the term is “reader macros”. What’s the big difference between the two types? Glad you asked. Would have been a long, uncomfortable pause if you hadn’t.

Unlike normal macros that are expanded AFTER post read. That is, taking what is on the text file (.lisp file), and converting it to be compiled. So basically, read is pre-compile time. Why does this matter? Because you can instruct the reader on how to “digest” stuff from the .lisp file, and then prepare it for compile time. So like a normal macro that tells the compiler how to expand itself to compile ready lisp code, a reader macro tells the reader how to transform the text into useful pre-compile code. And yes, a reader macro can create a normal macro. In fact, that’s what this example will show.

Ok, so back to the normal macro above; It still has the normal {} encasing. What if I wanted to encase it with something else? Say something like #| |.

 #| (+ 1% 2% 3%) '(4) '(5) '(6) | 

Normally this would cause all sorts of problems, a linguistic middle finger if you will. Don’t worry, lisp won’t get away with that.

(set-macro-character #\| (get-macro-character #\)))
(set-dispatch-macro-character #\# #\|
  #'(lambda (stream char1 char2)
      (let ((pair (read-delimited-list #\| stream t)))
        (cons (read-from-string "?>") pair))))

So as far as I understand it, somewhere there is a table of symbols that are reserved by Common Lisp. For instance, the right parenthesis or ). The “set-macro-character” basically allows the addition of new symbols like ]. It is telling the reader that ] is ).

Next part is the actual macro. If you take away the #\ characters from “#\# #\|” you’re left with “#|“. This is what the reader will look for in order to read the code that follows the “#|“. Essentially this has set up the ability for the reader to take in “#| |” without throwing an error. The in between is what the rest of the code handles.

For whatever reason (Again I’m new to this) the “set-dispatch-macro-character” needs a method that takes in three parameters: “stream” “char1” “char2”, the significance for this I have yet to see. However, the “stream” parameter is important to this macro. The stream is the code that is read in after the reader finds “#|“. The needed code is the start of the stream until it hits “|”. In this example that would be:

  (+ 1% 2% 3%) '(4) '(5) '(6)

To match the original macro, there still needs to be the leading “?>”:

  (?> (+ 1% 2% 3%) '(4) '(5) '(6))

And that’s where the “cons” comes in. I simply appended “?>” to the read in code “(+ 1% 2% 3%) ‘(4) ‘(5) ‘(6)” to give me:

  (?> (+ 1% 2% 3%) '(4) '(5) '(6))

Which is exactly the code I needed to call the original non-reader macro. So not only was it possible to completely ignore lisp syntax, it was also possible to nest a normal macro within the reader macro.

 #| (+ 1% 2% 3%) '(4) '(5) '(6) |
    -> (?> (+ 1% 2% 3%) '(4) '(5) '(6))
      -> (MAPCAR #'(LAMBDA (1% 2% 3%) (+ 1% 2% 3%)) '(4) '(5) '(6))
        -> 15

Euler 3 Just Got Lisped Up

“What is the largest prime factor of the number 600851475143?”

One thing I’ve learned so far from the euler stuff is that if seems too hard, I’m doin’ it rong. What I initially did is go from 2, tried to find any prime number that is a factor 60085…3, and keep updating the highest found. This was silly. In reality, I needed to start from 60085…3, find the largest factor of it, and keep going if it’s not a prime number. After all, the highest possible factor can’t be higher than 60095..3/2, prime or not. If that fails, then increase the divisor by one, and check if the other number is a prime.

600851475143 / n = x where n 2 -> ?
600851475143 / 2 = x
600851475143 / 3 = x
600851475143 / 4 = x

This meant I needed two parts, one to roll through all possible values of n until x was a prime.

(defun lowest-prime-divisor (start &optional (current 2))
  (if (and (= 0 (mod start current)) (is-prime-number (/ start current)))
    (/ start current)
    (lowest-prime-divisor start (+ current 1))))

As I wrote before, this is taking the original number (6800??adf…3), and start with dividing it by 2. What ever the remainder is, take it and check if it’s a prime. If so, return that. If not, divide by 3. I have no clue why I named it lowest-prime-number. Probably a case where my limitless intellect is proving that I am not nearly smart enough to understand it.

Here is the brute force prime number check. Essentially start a 2, use mod, and increase the iteration. This is done until either something mod iteration is 0, or the iteration is the same as the number being checked. It has a special kind of ugliness, and inefficiency.

(defun is-prime-number (start &optional (currentDivisor 2))
  (if (= start currentDivisor)
      (if (= 0 (mod start currentDivisor))
          (is-prime-number start (+ currentDivisor 1)))))

And I don’t have a macro this time. Mostly because I’m on 8 currently, and this is only the third post.

Common Lisp and How It Conquered the Euler Problem 2

So yesterday I took down Euler problem 1. Yeah, I’m just that good. In fact, only something like 250k of the entire world population (7 billion or so) got it right. That’s not even including people like Santa Clause. Elite level, here I am.

I would tell you what the second question asks, but that would mean I read it correctly the first time around. What I read was something like “Add up all even Fibonacci numbers up to the four millionth Fibonacci number.” Cake! Right off the bat I was going to do this tail recursive style, ’cause that’s the way an elite programmer like me does it. Now, I know I’d seen the cannon version of how to get the Nth Fibonacci number, but I chose to blaze some trails. (And I forgot what the cannon version was) The idea was instead of doing that whole (n – 1) and (n – 2) nonsense.

So to start there is 0 and 1. Then 1 and 1. Then 1 and 2. Then 2 and 3. Every iteration has a sort of shift where the right parameter becomes the left, and the new right was the old left + right. Sounds like a really easy recursion problem. Only thing missing is an iteration used to find the Nth Fibonacci. That will just be reduced by one every iteration until it hits 0.  Once that happens, the last number is returned.

  (defun fib (left right iteration) 
    (if (= 0 iteration) 
      (fib right (+ right left) (- iteration 1))))

And it would be called by:

  (fib 1 0 37)

Which, by the way, is 24157817.

So now I have a way to get the Nth, it’s time to add up all evens up to the 4 millionth Fibonacci number. Oh yeah.

 ;;This is needed to add the current Fibonacci number to the sum if it's even
  (defun adjust-sum(sum currentNumber)
    (if (evenp currentNumber) (+ sum currentNumber) sum))

 ;;And this is an update that keeps adding up the even Fibonacci numbers and stuff.
 (defun fibo (left right iteration sum)
   (if (= 0  iteration)
     (fibo right (+ right left)  (- iteration 1) (adjust-sum sum left))))

Now the site gave me the first 10 numbers: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. So adding up the even numbers in that list gets… eh… Oh! 44. Well time to see if the above bit of lisp works.

(fibo 0 1 10 0) ;;44

Yay. Well that’s easy. Next 4 million.

(fibo 0 1 10 4000000)

15 minutes later

Now the fun part about that solution is that I will never get a stack overflow. Bad part is that I have no idea how long it would take to add up 0 -> 4 millionth Fibonacci number. So at that point I was thinking I would have to somehow create a tree structure of parallel operations. Start with 4000000 / 2 and find the total in those two. To do that, I would halve those, and then halve again… ect, and sum up everything while traveling back up the tree. Or is it down? Whatever. I couldn’t believe how *(@#ing hard this second problem was. That was when I re-read the problem. Turns out I was supposed to add up every even up to 4 million. So the Fibonacci number closest to 4 million. Not the 4 millionth Fibonacci number. Then it seemed to be back to what I would expect for the second problem.

  (defun fibos (left right sum)
    (let ((adjustment (adjust-sum sum left)))
      (if (< right 4000000)
        (fibos right (+ right left) adjustment)

Basically every number found that is even, add it to the sum. That is until the right number is greater than 4 million. (Which would make the left number too high on the next iteration) At that point, add the left (If even), and return the sum. And guess what? It worked.

Now this wouldn’t be a lisp post if I didn’t add in some macro for over kill. After I failed to add up all even numbers up to the 4 millionth Fibonacci, I thought that maybe if I put them all in a list, and then added them up: magic would happen. Magic did happen, I killed the heap. I mean if adding two really big numbers was killing lisp, having a bunch of lists full of large numbers being added together should be fine, right? Make perfect sense. HOWEVER, one interesting thing did come from that: A macro. Here’s the original function for the array adding, pre massive tree idea. This just puts all into a list. I didn’t even get to the adding part.

  (defun fibl (left right iteration numbers)
    (if (= 0  iteration)
      (fibl right (+ right left)  (- iteration 1) (if (evenp left) (append numbers (list left)) numbers))))

Well I figured instead of just having a method call fibl to add all the numbers, just make a macro that would call fibl to get the list, then run an eval to add them all together. Why settle for simple, when a macro can make it way more complex. Although in my defense, when using macroexpand-1, I get to see the whole list of numbers before they are added.

  (defmacro fibl-bibl (a b c)
    `(eval (+ ,@(fibl a b c '()))))

With expansion:

  (macroexpand-1 '(fibl-bibl 1 2 100))

I got:

 (+ 2 8 34 144 610 2584 10946 46368 196418 832040 3524578 14930352 63245986
    267914296 1134903170 4807526976 20365011074 86267571272 365435296162
    1548008755920 6557470319842 27777890035288 117669030460994 498454011879264
    2111485077978050 8944394323791464 37889062373143906 160500643816367088
    679891637638612258 2880067194370816120 12200160415121876738
    51680708854858323072 218922995834555169026))

A list of Fibblenibble numbers. That was a lot for just one problem. Oh and for fun, here is the original golden function when adding all evens up to the 100000th number.


Project Euler: Question One… And A Pointless Macro

So for the something of it I am going to see how far I can get in the Euler Project Problems (Not sure if I should have capitalized “problems”). Basically finding solutions to questions no one has ever asked. If nothing else, this is a way to further my Lisp knowledge… so yes, this is in Lisp. Hide the children.

First problem is simply to add up all the numbers that are multiples of 3 and 5. It’s like a more boring version of FizzBuzz. Apparently that is possible.

So it’s not exactly a difficult problem. Essentially I just went with tail recursion. Don’t know what that is? Well it’s magic. This is typical recursion:

 def someMethod(current, end)
    if current == end
      return end
      return current + someMethod(current+1, end)

Basically the method calls will look like this:

(0 + (1 + (2 + (3 + (4..... end)...)

Because the preceding method depends on the current’s answer, that method call has to sit in memory. If end = 10000000… Stack overflow. Oh yeah.

Now some languages have something called “tail call optimization” which basically means all useful information is passed into the next method. IE the preceding method isn’t waiting for a return, because it supplied the next method with everything.

def someMethod(current, end, final)
  if current == end
    return final
    return someMethod(current+1, end, final + current)

The big difference here is that every iteration sends all information forward… as in there is no return “x + someMethod(…)” call that leaves the previous iteration on the hook for the current function’s return. Yay. Why does that matter? ‘cuz. Fine. Some languages are smart enough to forget about the previous call, because it no longer has a use. Kind of like garbage collection.

So to attack the original problem at hand, I used a simple tail recursion strategy. Every iteration with push the next number to check, and the updated total to the next.

def euler-one(currentNumber, total)
  if currentNumber == 1000
    //At the end, so just return the final tally
    return total
    if(currentNumber % 3 == 0 || currentNumber % 5 == 0) 
       //The currentNumber is divisible by 3 or 5 // so add it to the total, and increase the currentNumber
       return euler-one(currentNumber + 1, total + currentNumber)
       //The currentNumber is not divisible by 3 or 5 // so just increase the currentNumber, and leave the total alone
       return euler-one(currentNumber + 1, total)

Or in a real language:

(defun euler-one (currentNumber total)
  (if (= currentNumber 1000)
    (euler-one (+ currentNumber 1)
      (if (or (= 0 (mod currentNumber 3)) (= 0 (mod currentNumber 5)))
        (+ total currentNumber)

Of course this wouldn’t be a post by me if I didn’t over complicate it… MACRO TIME!

You might have read my macros primer thing (Most likely not), so this shouldn’t be to hard to understand… right??

What I was shooting for is a macro that would not only do the above, but would allow for as many numbers to check as the divisorable thing… So instead of:

(euler-one 1 0)

Where “1” is the starting number, and “0” is the starting amount. Instead I want to do this:

(euler-go 3 5 7)

Where “3”, “5”, and “7” are the numbers to check if the current number is divisible by. Pretty sure that made sense… Ok, so!

(defmacro euler-go (&rest args)
     (defun euler-one-a (currentNumber total)
       (if (= currentNumber 1000)
         (euler-one-a (+ currentNumber 1)
            (if (or ,@(mapcar (lambda (x) `(= 0 (mod currentNumber ,x))) args))
              (+ total currentNumber)
     (eval (euler-one-a 1 0))))

And here’s what it looks like expanded.

 (EVAL (EULER-ONE-A 1 0)))

Looks pretty much the same right? ‘Cept for the PROGN thing. PROGN basically just runs everything in order, and returns the result of the last section. So this macro actually creates the euler-one-a method, and then calls it with the “(EVAL (EULER-ONE-A 1 0))”. The important part is the section that creates the divisor check:


Which looks an awful lot like:

(if (or (= 0 (mod currentNumber 3)) (= 0 (mod currentNumber 5)))

From the original method. HOWEVER, the one thing the macro can do is make as many or checks as I want. Say I want to use 3,5,7,9:

(euler-go 3 5 7 9)

The expansion is:

                (= 0 (MOD CURRENTNUMBER 7)) (= 0 (MOD CURRENTNUMBER 9)))
 (EVAL (EULER-ONE-A 1 0)))

And the macro creates all four. How is that possible? One line in the macro:

(if (or ,@(mapcar (lambda (x) `(= 0 (mod currentNumber ,x))) args))

Remember, with macros there’s a step where you can create more code BEFORE the final expansion. What that line says is to take all the values in args (3,5,7,9), and create a “(= 0 (MOD CURRENTNUMBER X)” where X is 3,5,7,9. For people more familiar with c#, pretend you are creating a string.

"(if (or (" + args.Select(x => "(= 0 (mod currentNumber " + x + ")) ".Aggregate(new StringBuilder(), (builder, current) => builder.append(current)).ToString() + ")";

Or something like that. The difference is lisp is creating actual code, not strings. Anyways, that’s it. Yeah. This is awkward.

Common Lisp: Intro to Macros… Because I Only Know Enough for an Intro

I am extremely new to Common Lisp, and macros. I’m willing to bet that anything shown here can be improved.

Been reading through Paul Graham’s On Lisp which is probably not a real “Intro to Lisp”, but well within the grasp of my super interlect. Well at least it was today when I had a breakthrough on macros. I had some introductory stuff on macros when I was perusing through various ancient texts of the language of Clojure. However, I never really looked into to macros much since I was trying to figure out things like how to set up a web server in Clojure. For whatever reason, call it divine intervention or maybe vision inducing exhaustion, it dawned on me to read On Lisp. I figured that if I were to learn macros, I might as well learn them from a person who I can only guess is Lisp: Paul Graham. Turns out, this was a good choice.

Now to start, understanding what a macro is, I have to introduce the word “homoiconic”. It’s a really fancy word that means that a Lisp code is compromised of data structures. In simple terms: Lisp is built on lists. For example:

(+ 1 2 3)

Is that code or a list? Yes. Why is this important? Because any code can be from combining lists together, or by taking a smaller list and expanding it out into code. Unlike other languages that might use a method to evaluate a string representation of code, or some kind of preprocessor directive, you are creating real code that needs nothing special to read/evaluate it. A kind of useless example of this is taking a method, and making it into a macro:

  (defun average (x y)
    (/ (+ x y) 2))

And the macro:

  (defmacro average-macro (&rest args)
    `(/ (+ ,@args) ,(length args)))

Completely obvious, am I right? Nothing seems odd or foreign… HRAHARAHRAHAR

Ok sooo… The main thing about macros is what is supposed to be evaluated at the time the macro is expanded, and what to ignore. Essentially when the macro is expanded, you can have method calls to create code to add to the final expanded code, or code that will remain untouched to become a part of the final product. It’s kind of an odd thing to understand. After all, it means you have to think in more than just one dimension. Think of it like you are concatenating a string. In something like c# you might have a string built like this:

string function ReturnFinalString(name) {
  return CreateFormalGreeting(name) + ".  It is nice to meet you on this fine " + RetrieveTheDayName(DateTime.Now);

Ignore that I am using the + string concatenation junk instead of string.format, or StringBuilder. Just wanted something easy to read.

As you can see, there are parts of the string that don’t need any changing, because they are in a final state. (Meaning that’s exactly how they will appear in the final string) However, there are other parts that need the result of an evaluated method. Once those method returns are resolved, you get a single string. A macro isn’t too much different in concept. Instead of creating a list of characters, you are creating lists of code.

Ok so now it’s time to break that macro down. Remember, macros are about what to evaluate, and what to ignore.

  (defmacro average-macro (&rest args)

First two parts should be easy to understand, but the third one is misleading somewhat. What looks like two parameters is really just one: args. The &rest is just syntax for “What ever arguments are left.” For instance, say this macro was more generic where it would take in a function (add, subtract, whatever), and also some numbers. The syntax would be:

  (defmacro do-something (methodToUse &rest args)

The call would be like:

  (do-something add 1 2 3 4)

“add” would be the “methodToUse”, and 1 2 3 4 would be “args”. An important point is that anything passed the named parameters gets lumped into a list. So if I was completely stupid (I’m only partially), and didn’t know what I was supposed to sent into “do-something”, I might do this:

  (do-something add 1 "a" someVariable derp)

The “args” would be (1 “a” someVariable derp). Most likely the macro would throw an error if you tried to use it in the REPL, but the point is just to realize how “&rest args” works.

That was the easy part. Now for the weird part.

`(/ (+ ,@args) ,(length args)))

Looks like a dragged my face across the keyboard, or PERL. Either way, the syntax is pretty goofy looking at first… And even after that. However, the idea behind it isn’t that bad.

Remember how I said something about it all being about what to evaluate, and what to ignore? Well right off the bat, the macro is told to ignore everything. Why? The back quote.

`(... stuff here...)

Without any special characters, the macro will just ignore everything within the parenthesis. So if I did this:

  (defmacro add-this ()
    `(+ 1 2))

Everything in there will not change when the macro is expanded. So basically that’s a really stupid macro. What’s the best thing to do with a useless macro? Make it more complex.

  (defmacro add-this ()
    `(+ ,(+ 1 2) 2)) 

New syntax, the comma. The comma is the opposite of the back quote. It basically says not to ignore what’s there, and to evaluate it. Before the final product, the (+ 1 2) will be evaluated, and that result will end up in the final expansion. Without that comma, the final product would be:

(+ (+ 1 2) 2)

But it really is:

(+ 3 2)

The difference is subtle, but it’s everything. What this means is that in the version with the comma, the (+ 1 2) is being evaluated, and its result (3) is then applied to the macro expansion. Given this example, it’s hard to understand what use that could be, but it will be completely obvious when the last part of the original macro is explained.

`(/ (+ ,@args) ...

So the comma is used to make sure that parts are evaluated for the final expansion, but what is @? @ is an interesting concept that also has large implications, despite the textbook explanation being underwhelming. The , followed by the @ means that it will strip the outermost parenthesis off. Yeah, boring BUT critical. I had explained that &rest args dumps all remaining arguments into a list, right? Well what if you needed to use the values in “args”, but not as a list.

What if I created a simple macro like:

  (defmacro add-that(&rest args)
    `(+ ,args))

And the call would be:

  (add-that 1 2 3)

Now + can’t be used with list, because it expects single values like:

  (+ 1 2 3)

Now in this macro, I did this:

  (defmacro add-that(&rest args)
    `(+ ,args))

Which says to ignore the +, and evaluate “args”. Well we know that the macro call stuff 1 2 3 into one list. So as is, if this is expanded, it will look like this:

  (+ '(1 2 3))

Bad. How can that be fixed? The @ sign.

  (defmacro add-that(&rest args)
    `(+ ,@args))

This will expand to:

  (+ 1 2 3)

As you can see, the ‘(1 2 3) “args” was evaluated to just “1 2 3” before the final product.

With that all in mind, time to go back to the original semi-useless macro:

  (defmacro average-macro (&rest args)
    `(/ (+ ,@args) ,(length args)))

Read out loud it says:

1) ignore the /
2) ignore the (+
3) remove the parenthesis from args
4) ignore the )
5) get the length of args
6) ignore the )

The interesting part to note is step 5. This shows the power of macros, even in a lame example. To make sure the average of x number of er numbers, there has to be a total count of numbers to divide by. When looking at the original function that this macro was based on:

  (defun average (x y)
    (/ (+ x y) 2))

If you want to find the average of 3 numbers, you hosed. BUT since the macro is able to take the length of the args list, and then apply that value to the final expansion; You can easily find the average of however many numbers you want. Remember, the “,(length args)” part is able to resolve that count BEFORE the final expansion is evaluated. This can be shown using macroexpand-1:

  ;; When the macro is expanded
  (macroexpand-1 '(average-macro 1 2 3 4 5))
  ;; Becomes:
  (/ (+ 1 2 3 4 5) 5)

As you can see, the final product has 5 in place of ,(length args). Magic.

  ;; When the macro is expanded
  (macroexpand-1 '(average-macro 1 2 3 4 5))
  ;; Becomes:
  (/ (+ 1 2 3 4 5) 5)

This macro is kind of pointless, because it could be done with a better function than the original one. However, the concepts are what matter.
Now for something more interesting. What if you don’t like the way that functions are declared? I kind of do. I started with Racket (Scheme) before I ended up at Common Lisp. In Racket, there is a uniform definition.

(define (name argument) ...)

But with Common Lisp, the “name” is outside the argument list. Well with macros that can change. And rather easily:

;;(DEFUN X () (+ 1 X))
(defmacro define (head &rest body)
  `(defun ,(car head) ,(cdr head) ,@body))

And it would be called like this:

(define (test-it x y) (+ x y))

Which is syntactically different than the Common Lisp way:

(defun test-it (x y) (+ x y))

How did I do that? There is a little trickery involved, but nothing hackish. Just opinionated. (Or Convention over Configuration as some might call it) Time to break it down.

(defmacro define (head &rest body)

Here’s the start of the trickery. I know that anything that is in “body” is what’s left over after “head” is set. Right off the bat, that could be an issue. After all, “test-it” not only needs the function name, but has two parameters in “x” and “y”. Doesn’t take long to realize that “x” and “y” will somehow have to be accounted for. This means they will end up in “head”, or “body”. In this case, “head”.

`(defun ,(car head) ,(cdr head)....))

And that’s what I mean about opinionated. I expect that “head” is actually a list. A list that starts with the function name, and then has all the parameters. That’s where car and cdr come in. (car means grab the first item in the list, and cdr means grab all BUT the first item in the list) My macro expects that the first item in the “head” list is the function name: “test-it”. It then expects anything else in “head” is a parameter. When the part above is evaluated, it will ignore “defun”, get the first item “test-it”, and the get the list of remaining items. Since cdr returns a list, the function definition doesn’t need anything special done to the parameters.

`(defun ,(car head) ,(cdr head) === (defun test-it (x y )...

After that, the rest is easy.

,@body === (+ x y)

Ok, how about something even more interesting. Say you wanted to completely change the syntax for lambda expressions. This is the normal way:

(mapcar (lambda (x) (+ 1 x))...)

I say, “To hell with that.” I also say, “I want something like this:”

(-> x y z (+ x y z))

Not only did I remove the “lambda” keyword, I removed the parentheses around the parameters. HOW CAN THIS BE?!?! More trickery.

(defmacro -> (&rest arguments)
  (let ((reversed (reverse arguments)))
    (let ((last (car reversed))
          (undone (reverse (cdr reversed))))
    `(lambda ,undone ,last))))

And that’s it. Good night.

Oh, you want an explanation, so be it. The idea behind this is that I will expect the call to have this: n1 n2 n3 … nx (method call). This means that when all items smashed into “arguments”, everything but the last item in the list is a parameter. So no matter how long the “arguments” list is, the most important thing to remember is that ONLY the last item is the body of the function. I think I just wrote the same thing twice, but whatever. Now to break it down.

(defmacro -> (&rest arguments)

Just the typical start to a macro.

(let ((reversed (reverse arguments)))

Here’s something a bit new. As the other macros I showed didn’t need any fields, I didn’t use let. This time the “arguments” field is taken, and then reversed. Why? So that I can do this:

  (let ((last (car reversed))
    (undone (reverse (cdr reversed))))

I took “reversed” from the original let statement, and then retrieved two things from it: The head (Which is actually the last item of the original “arguments” list, but now it the first in the reversed list), and all the rest re-reversed.

arguments == ‘(x y z (+ x y z))
reversed == ‘((+x y z) z y x)
last == ‘(x y z)
undone == (x y z)

The reason why “undone” has to be reversed it that when the “arguments” list was reversed, the “x y z” ended up as “z y x”. If I hadn’t reversed it, the parameters in the method would be reversed. This would be a large issue.

(z y x (+ x y z))  ;;BAD
(x y z (+ x y z))  ;;GOOD

Last part:

  `(lambda ,undone ,last))))

Oh yea, there was an actual part to be expanded in the macro. Why wasn’t ,@ used? Remember that the lambda syntax is:

(lambda (x y z) (+ x y z))

Meaning that the parenthesis that surround “undone” and “last” are OK to keep.

Done yet? Too bad, because here’s one more. The last macro has room to improve from a structure stand point (as I am new to Lisp), but also on a conceptual level. The next big thing would be to not have to bother with declaring the method parameters for the lambda clause. I want to turn something like this:

(mapcar #'(lambda (x y z) (+ x y z))


(?> (+ z y z) '(1) '(2) '(3))

Where the ‘(1), ‘(2), and ‘(3) are the values that will be passed into “mapcar”. As you can see, I have no declaration of the lambda or its parameters. Crazy, I know. The idea is to have a macro not only create the needed mapcar and lambda syntax, but to generate one parameter declaration for every argument… no matter how many arguments there are. The caveat here is that the generated argument names shouldn’t be something so common as x, y, or z. For this demo I’ll be using a list of numbers that have the “%” character appended to them. So instead of the “x y z” above, it will be “1% 2% 3%”. The final expansion should be:

(mapcar #'(lambda (1% 2% 3%) (+ 1% 2% 3%))

Before I get to the macro, I need a couple of helper methods.

First I need something that will generate a list of numbers as string. The reason why is that later I will concatenate each number string with the “%” character to have a basis for the created parameter names.

;;This creates a ascending list of numbers as string.  
;;  (numbers 5) == ("1" "2" "3" "4" "5")
(defun numbers (count &optional (finalList '()))
  (if (= 0 count)
      (numbers (- count 1) (append (list (write-to-string count)) finalList))))

Now I need something to concatenate the number strings with “%”, AND turn them into legal parameter names.

;;This is used to take two concatenated strings, and turn them into potential parameter names
;;  (create-parameter-name "1" "%") == 1%
(defun create-parameter-name (x y)
  (read-from-string (concatenate 'string x y)))

Finally I need a method to use the other two method to create the needed list of parameters:

;;This is used to dynamically create the needed parameters for a lambda expression
;;  (create-placeholders "a" "b" "c") ==  '(1% 2% 3%)
(defun create-placeholders(arguments)
  (let ((argumentCount (length arguments)))
    (mapcar #'create-parameter-name  (numbers argumentCount) (make-list argumentCount :initial-element "%"))))

And here is the macro:

(defmacro ?> (conversion &rest args)
  `(mapcar #'(lambda (,@(create-placeholders args)) (,@conversion)) ,@args))

(macroexpand-1 '(?> (+ 1% 2% 3%) '(4) '(5) '(6)))
(MAPCAR #'(LAMBDA (1% 2% 3%) (+ 1% 2% 3%)) '(4) '(5) '(6))

1) Ignore (mapcar #'(lambda(
2) Create the parameters based on the length of args
3) Ignore ) (
d) Evaluate the contents of conversion (the passed in method), and remove the surrounding parenthesis
5) Ignore the )
VI) Evaluate args, and remove the surrounding parenthesis
7) ignore )

Yay. Time to stop for now.