Clojure Multi Method Chain with Partial

In my last post I had mentioned that there could be an improvement to
the code below:

  ((partial sort-by :Name))
  ((partial drop (* page-number items-per-page))
  ((partial take items-per-page)))

Simple method chain taking advantage of partial methods. That might
be fine for lesser beings, but not for someone so ruggishly handsome
as me.

To take an easy example that can be run in the REPL:

  (range 20)
  ((partial drop 5))
  ((partial take 5))
  ((partial apply +)))

Create a list of 1 to 20, drop the first 5, take the next 5, and add
them. You know, completely useless in the real world. What irks me
(Yes I used the word irks) is:

((partial ... )).

The reason for the double parenthesis is that as the chain moves to
the next step, it applies the chain result to it. If it were only:

(partial drop 5 [1 2 ... 20])

it would have tried to apply the range list to the partial call.
Uh oh… not good. Now look at it from the correct way:

((partial drop 5) [1 2 ...20])

Now it actually works. Partial is created, and THEN the list is
applied to it. Weeee!

So what’s next? Removing the partial thing. What I want, and you
should want too, is this:

  (range 20)
  (drop 5)
  (take 5)
  (apply +))

A fair bit less typing, and less words to read. Win and Win.

Now when it comes to macros, It’s a goog idea to remember that macros,
for the most part, is just about assembling lists. After all, Clojure
is a part of the Lisp family. Therefore, there is no difference
between a list, or code.

So to get underway, what do we need? A really cool, and novel name
for the macro.


Next, there needs to be a parameter list for the macro to use. There
are two parts of the original code: The list, and the list
manipulators. Because the list, in this context, is the odd ball, it
gets its own parameter. The manipulators get smashed into one group.
Don’t cry for them. Not them.

(defmacro |-> [original & items]

That way easy. Time to go home.
Ok so that I’m home, I’ll move to the next step:

(defmacro |-> [original & items]

That the -> an obvious given. The -> is needed. The
~original takes the value in original (range 20), and will resolve it
at expansion time.

Why not just:

(defmacro |-> [original & items]

Because if you expand that, the word ‘original’ will just be there,
not the (range 0 20) that it represents.
~original produces:

  (range 0 20)

original (with no ~) produces:


Next step is to figure out how to get this:

  ((partial drop 5))
  ((partial take 5))
  ((partial apply +))

from this:

  (drop 5)
  (take 5)
  (apply +)

Remember, we are creating code by manipulating lists. What we need is
a tranformation from (drop 5) to ((partial drop 5)). How can this be
done? Cons.

(cons `partial %)

Ok, why cons? Every item in the items list is itself a list.

(drop 5)

If “cons” the keyword partial to it I get:

('partial drop 5)

Essentially I am making a new list by attaching partial to the old
one. However, that doesn’t get what is needed.

((partial drop 5))

So guess what? Cons again.

(cons (cons 'partial %) '())

This time I consed the new partial/drop list to an empty list.

(('partial %))

If only there was a way to automate the creation of a list of the
converted items…

(map #(cons (cons 'partial %) '()) items )


Now to put it all together:

(defmacro |-> [original & items]
    ~@(map #(cons (cons 'partial %) '()) items )))

The ~@ is just so that it evalates the map call/result at expansion
time. The @ gets rid of the surrounding parenthesis of the list that
map creates.

Now you do exciting things like:

  (range 0 20)
  (drop 5)
  (take 5)
  (map #(+ 1 %)))


Clojure: How to Chain Array Functions Using Partial

Wrote this just recently as a part of way to mock a database query for testing JavaScript controls.

(defn retrieve-subject-items [page per-page sort descending]
  (take items-per-page
        (drop (* page-number items-per-page)
              (sort-by (to-key sort) subject-items))))

Is the “why” important? No. What is important is that all of these list functions have one thing in common:

take =    f(int list)     => list
drop =    f(int list)     => list
sort-by = f(keyword list) => list

The last parameter needed is a list. Mind blown, I know.

This screams for partial functions. What are partial functions? They are functions created to “wrap” existing functions, just with some of the arguments already taken care of. For example:

function drop (numberToDrop listToUse)

Easy enough. It takes in a list, and the number of items needed to be dropped from said list. Now what if you knew that under a certain circumstance, the top 5 will always be dropped. Say there are three lists: MathTestScores, EnglishTestScores, and BiologyTestScores where the “scores” are numbers from 1-100. One rule is no matter which list is used, the top 5 scores will be removed to help with a grading curve. You could do something like this:

drop(5 MathTestScores)
drop(5 EnglishTestScores)
drop(5 BiologyTestScores)

As you might notice, there is a pattern here. You could create a method that takes in a list, and removes the top 5. Nothing wrong with that.

function drop5(list)

Now, as dumb as this might be, there is some reason you’re told to drop 5 from all lists, and add the sum of each list together. Yes, this example is train wreck from a “makes sense” standpoint. Or it sounds like how to calculate a baseball statistic. Either way: Convoluted. But you are merely the worker. Yours is not to ask why.

You might get something like this:

sum = drop5AndSum(MathTestScores 0)
sum = drop5AndSum(EnglishTestScores sum)
sum = drop5AndSum(BiologyScores sum)


sum = 
    (drop5AndSum EnglishTestScores 
     (drop5AndSum MathTestScores 0)))

Wonderful. Now lets say you use a language that has method chaining. Basically the preceding method sends its result to the following method. Sort of like the example right above this. Only difference is the order is kept.

sum = drop5AndSum(MathTestScores, 0) -> drop5AndSum(EnglishTestScores, *sumFromLastCall*) -> drop5AndSub(BiologyTestScores, *sumFromLastCall*)

Problem with this is that the drop5AndSum function needs two parameters, but it only produces one. So syntactically you’re &$!@ed. This is where partial methods come in. The goal is to get the call to drop5AndSum to only need one argument: the result from the preceding drop5AndSum function.

sum = drop5AndSum(MathTestScores, 0) -> drop5AndSum(EnglishTestScores) -> drop5AndSum(BiologyTestScores)

BUT HOW?!!? Partial methods… and man whorin’.

partialEnglish = dropAndSum5(EnglishTestScores)
sum = drop5AndSum(MathScores, 0) -> partialEnglish

The function the follows “drop5AndSum(MathScores, 0)” no longer needs to have the list passed in. It just needs a number, the sum, and it will do its thing. How is that possible? Look at the original function definition:

drop5AndSum = f(list, int) => int

Now look at partialEnglish

partialEnglish = f(int) => g(list, int) => int

As you can see, partialEnglish takes in the preceding sum result, then applies that to the drop5AndSum function.

Why bother with this? Easier to understand the order of operations.

mathSum = drop5AndSum(MathTestScores);
englishSum = drop5AndSum(EnglishTestScores);
biologySum = drop5AndSum(BiologyTestScores);
sum = 0 -> mathSum(MathTestScores) -> englishSum(EnglishTestScores) -> biologySum(BiologyTestScores)

The intention is a little more readable than the (drop5AndSum … (drop5AndSum … (drop5AndSum …))).

What does this have anything to do with the original block I had at the start:

(defn retrieve-subject-items [page per-page sort descending]
  (take per-page
        (drop (* page 5)
              (sort-by (to-key sort) subject-items))))

Because the order is actually right to left, it may not read well. However, if it read from top to bottom, readability should increase.

  ((partial sort-by :Name))
  ((partial drop (* page-number items-per-page))
  ((partial take items-per-page)))

Now with somewhat meh keywords ignored (Ahem “partial”): It’s pretty obvious what the order of operations is, as is the overall intent. Start with a list, sort it by name, drop a few, take a few. Despite the ugliness of “partial”, it is still far more readable.  Good new is, if you’re using Clojure, you can remove the “partial” part altogether with a macro.

Also if you’re using Clojure, you might notice the double parenthesis.  This has to do with the need to resolve the returned partial method in order to apply it to the passed in chain result.

Google Closure and How to Create a Batch File for Running ClojureBuilder

Learn how to create a batch file on Windows to use the Google Closure compiler.

Hoping this will save someone time in the future; whether the future is bright and shiny… or robotic apocalypse. One of the relatively few issues I’ve had with Google Closure was moving from calcdeps (I think that’s what it was called) to ClosureBuilder was setting up a batch file to run it. With calcdeps, it was mostly just naming a bunch of folders, and it did the rest. When I moved to ClosureBuilder, it wasn’t that easy. At first I panicked, and promptly jumped through a second story window, then I decided getting used to the new compiler is healthier in the long run. Turns out that even if ClosureBuilder expects actual namespaces to include, it’s better in the end as it makes it much easier to include/uninclude a particular namespace incase there’s a need to pick and choose. Here’s an example of the batch file I created to compile a “live” (Not test”) version:

python c:/lib/closure/closure-library/closure/bin/ ^
//Optional if you are running the 32 bit version of jvm/jre
--jvm_flags="-d32" ^
//This is where all the closure files exist
--root="c:/lib/closure/closure-library/" ^
//This is the folder in the project that has all the JavaScript files.
--root="content/script/live/" ^
//Here are the namespaces in that JavaScript folder that I want to include
--namespace="src.base.helper.arrayHelper" ^
--namespace="src.base.helper.constants" ^
--namespace="src.base.helper.domCreation" ^
--namespace="src.base.helper.domHelper" ^
--namespace="" ^
--namespace="src.base.control.gridBuilder" ^
--namespace="src.base.control.pager" ^
--namespace="" ^
--namespace="" ^
--namespace="" ^
--output_mode=compiled ^
--compiler_jar="c:/lib/closure/compiler.jar" ^
//This is optional if you want the super duper minimized version on compile.
//  I typically don't use the simple version, because I had found issues where
//   it works with simple, but not advanced.
--compiler_flags="--compilation_level=ADVANCED_OPTIMIZATIONS" ^
//This is where you want to save the compiled result.  I've found that it is easier
//  put the batch file in the web root, and have it use a relative path rather than
//  having to give it a drive path like c:\web\something\somethingElse\content...
--compiler_flags="--generate_exports" > "content/script/live/final.js"
//I keep this here for when I have to be on a computer with the 32 bit version of 
//  jrm/jvm.
rem --jvm_flags="-d32" ^

As you can see, it’s actually not all that complicated.

Ruby, Sinatra, and static content (You know, JavaScript)

Sinatra: A quick look at how to set the default static content folder name to anything other than “public”.

Good news: If you were searching on how to server up static files with Sinatra, you’re in luck.

Bad news: I’m using Ruby…

As I stumble through the use of Sinatra (and to a lesser extent Ruby) one of the first issues I ran into was self loathing, followed by a need to have the server actually find my main JavaScript and CSS files. Well this is the current set up in a really poorly done folder rendition:

- content/script/live
 |-- final.js
- content/style/css
 |-- final.css
- view
 |-- main.html
- base.rb

Pretty simple.

At first main.html had what I thought would be the correct link to both:

  <link rel="stylesheet" href="content/style/css/final.css" type="text/css"/>
  <script type="text/javascript" src="content/script/live/final.js"></script>

Turns out, that wasn’t right. After a few attempts to get the server to actually do what it’s supposed to (and there by giving my powers of deduction too much credit), I went a huntin’.

So today I learned that Sinatra by default expects there to be a folder named “public” that would hold the /style, and /script folders. Go figure. Being stubborn as I am, I didn’t want to put them in a parent folder named ‘public’, I wanted it name ‘content’. Don’t hate. Note: the folder has to be on the same level as the file that was used to start the server.

So this is more than possible. Just takes one line it the base file (the one you used to start your server):

require 'sinatra'
require 'json'

set :bind, ''
set :public_folder, { File.join(File.dirname(__FILE__), 'content') } <--- HERE

Yes there are five lines… No the other four aren’t part of this problem… You done?

Ok so it’s now looking at that folder, but there’s still one more step. Remember those links?

  <link rel="stylesheet" href="/style/css/final.css" type="text/css" />
  <script type="text/javascript" src="/script/live/final.js"></script>

Just had to remove the content folder mention in the links, and everything is happy. Except me… because it’s Ruby.

Google Closure: An Enter Key Press

How to set up an event handler for when the enter key is pressed withing the Google Closure system.

Real quick thing which was getting the enter key to be handled on press in an input/textbox… though probably other things.,, function(a) {
  if(a.keycode === 13) {

This assumes that 13 is the universal id for the enter key. Not sure if there is a case of browser dependent key codes.

Clojure: Chaining Lamba Expressions that Act Like Partials

Really simple one. Say you have a chain like this:

(let [username (:username (?retrieve-value result))]
  (let [possible-error-message (text-is-empty username "Username")]
    (add-an-error-message result possible-error-message)))))

Pretty normal, and boring… and not super easy to read. Now this might happen only to someone who is rather new to Clojure (ME), but I figured I’d post it anyhow. Because I am that cool.

Using the -> macro (if you don’t know what that is, look at the Notes below), and lambda expressions (anonymous methods), it can be rewritten to remove a lot of the noise.

  (retrieve-value result)
  (#(:username %))
  (#(text-is-empty % "Username"))
  (#(add-an-error-message result %)))

That does the exact same thing as the original method, but cleans it up rather nicely. Though it still isn’t super mega ultra hyper readable…dx, it is still much easier to determine what is going on. Now the one thing needing to be noted is the extra () around the lambda expression. Because #(:username %) actually returns the method it creates, the second pair of () is used to call it with the value returned from (retrieve-value result). A little annoying, but really not that big of a deal.


The -> macro

-> is used to chain methods together. Say I have two function signatures (PSEUDO CODE ALERT):

  f() :string
  g(string) : string

I could call them like this:


With the -> operator I can do this:

f() -> g

As you can see the -> takes the result from “f”, and pushes it into “g”.

The # macro:

This is used to shorthand the normal lambda expression syntax.

(fn [a] (:username a))

Is the same as:

#(:username %)

Somewhat like the => operator in C# is used to replace the old anonymous method syntax from 2.0.

JavaScript DSL Because I’m Tired of Writing If.. If…If…

A little while ago a co-worker had expressed a dream of his to create some kind of language agnostic standard for validation. Without actually listening to what he meant by that, I set forth on doing this for JavaScript. I wanted to Lisp it up, as I am that kind of zealot. The idea was simple, provide a list like structure for describing the validation needs, but not make it a complete cluster *($#. I got the first part, not sure about the second. Essentially I wanted something like this:

 var rules =
      ('is not empty' 'Username is required.')
      ('is not longer than' 7 'Username is too long.'))

Where ‘Username’ is the name of the property needing the validation, and the ‘7’ is the maximum length, and the last part is the error. But, seeing as this was JavaScript, I had to do something a little more rigid.

Now for what the rules would look like:

 var rules =
      ['is not empty', 'Username is required.'],
      ['is not longer than', 7, 'Username is too long.']],
      ['is not empty', 'Name is required.']],
      ['length is between', 4, 6, 'Password is not acceptable.']]];

As you can see, the rules turn out to be very readable. On top of that, since it is only a list, converting a json based array to the rules should be pretty easy. The advantage of that would be the ability for a server response to contain the rules at which time the interpreter would match them to the methods. Thus providing a way to help with consistency of error messages, and constant values like in the password rule above. Something that is a pain in the #@@ some… all of the time.

The structure is fairly simple. [Property name [[validation need][extra parameters][error]…..[validation need][extra parameters][error]]] Essentially every property that is going to be validated can have n number of validation methods “attached” to it. Now one catch is that the object being validated has to have a matching “Property name”. Kind of falls into the “opinionated programming” side of things.

For this example, there will be three fairly generic validation methods. The methods either return null, or an error message. Over simplistic much?

 function isNotEmpty(toCheck, propertyName, error, rest) {
    return toCheck[propertyName] === '' ? error : null;

  function isNotLongerThan(toCheck, propertyName, error, rest) {
    return toCheck[propertyName].length > rest[0] ? error : null;

  function isBetween(toCheck, propertyName, error, rest) {
    var length = toCheck[propertyName].length;
    return (length < rest[0] || length > rest[1]) ? error : null;

And here is an example of how to attach the english to methods:

 var methods = [
    ['is not empty', isNotEmpty],
    ['is not longer than', isNotLongerThan],
    ['length is between', isBetween]];

I created a pseudo method look up table to match a much more “english” name for the validation method needed. Not exactly brilliant, and is sort of cheating. What would be nice is to actually read the english, break it down, and create the functions on the fly. BUT this works for now. That whole english breakdown I’ll attack at some point. After all, this was a sort of thought experiment.

The interpreter takes in the rules, matches the method, and send the extra values if needed. For example,

   ['length is between', 4, 6, 'Password is not acceptable.']

Is matched to:

  isBetween(toCheck, propertyName, error, rest)

Where “rest” is the 4 and 6. Rest is a carryover from Commmon Lisp’s &rest. It’s a collection of things that will be broken down by the validation method. Just think of them as optional values.

 var length = toCheck[propertyName].length;
  return (length < rest[0] || length > rest[1]) ? error : null;

There are two parts to the interpreter, but the first part is merely rolling through the rules, and making a call to this: = function(propertyName, methods, innerRule, find, car, cdr, peek, sink) {

 //Find the method that matches the english phrase
    var methodPair = find(methods, function(method) {
        return car(method) === car(innerRule);

 //In Closure the find method returns the whole matched "row", so I need the method which is the second column.
    var methodToUse = peek(methodPair);

    return function(obj) {
        var error = peek(innerRule);                           //error is the last index
        var values = sink(cdr(innerRule));                     //get everything but the error  
        return methodToUse(obj, propertyName, error, values);  //construct the validation call

car, cdr, sink, peek? The *(&^ are those? First two are carry overs from Common Lisp too. Car is just taking the first item of a list, if there is one.

  (car '(1 2 3)) ;;  1

Cdr returns a new list that is everything but the first item.

  (cdr '(1 2 3)) ;; '(2 3)

Haskell refers to them as Head and Tail. Clojure has First, and Rest. ect. ect. ect.

sink is used to get all but the last item in the list. Everything but the kitchen sink. Eh? Eh? Sigh. (The code for them can be seen here.).

peek is actually just a parameter cover for the goog.array.peek method. It gets the last element of an array. Remember, the structure is very specific. [validation need][extra parameters][error] Because of this, it’s easy to break down each rule into its respective parts using simple array manipulation.

Now at this point I only have created the method list creator (“Interpreter”), and haven’t created anything for running the validation. However, the code below is a rough estimate of how that would work.

 var result = interpret(rules, methods);

 var toValidate = {'Username': '12345678', 'Name': '', 'Password': '123'};
  for(var i = 0; i < result.length; i++) { something.innerText += '\n' + result[i](toValidate); };

The glaring issue with that is that I’m not removing empty strings. Other than that, it works. The working example is in the example folder for this repository. The removal would be nothing more than using a map -> filter type method chain.

 var validationMesssages =, function(item) { return item(toValidate); };
  return goog.array.filter(validationMesssages, function(message) { return !goog.string.isEmptySafe(message); });

Or something like that… probably not exactly like that unless you’re in with the Closure, or are stuck with Jsomethingry.

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.