title: How to parse pure functions
body: <p>Let's say you have the following function</p>
  
  <pre class="lang-js prettyprint-override"><code>var action = (function () {
  
    var a = 42;
    var b = 2;
  
    function action(c) {
      return a + 4 * b + c;
    }
  
    return action;
  }());
  
  // how would you parse action into it's serialized LISP / AST format?
  var parsed = parse(action);
  </code></pre>
  
  <p>Is it possible to have a function that takes a reference to the function <code>action</code> and outputs say the LISP format <code>(lambda (c) (plus (plus 42 (multiply 4 2)) c))</code></p>
  
  <p>We're allowed to put some restrictions on what <code>action</code> can be.</p>
  
  <ul>
  <li>the body should only be a single expression</li>
  <li>it should be a pure function</li>
  <li>any free variables are constants</li>
  </ul>
  
  <p>The main question is given a function you can invoke with a range of inputs and it's source code can you discover the correct value to substitute the free variables with?</p>
  
  <p>For the above example you know that a and b are constant and you could intellectually plot the output for a few values and see the pattern and then just know what the constants are.</p>
  
  <h3>Question:</h3>
  
  <p>How would you write a function that takes a function reference and it's source code and produces some form of AST for the function with any free variables substituted for their run-time values.</p>
  
  <p>An example of an AST format would be the LISP equivalent of the code.</p>
  
  <p>I basically want to serialize and deserialize the function and have it behave the same</p>
  
  <p>It should be noted that the problem becomes trivial if you pass <code>{ a: a, b: b }</code> to the analysis function. That would be cheating.</p>
  
  <h3>Use-case:</h3>
  
  <p>I want to generate a language agnostic form of a pure JavaScript function so I can effectively pass it to C++ without requiring the user of my library to use a DSL to create this function</p>
  
  <p>Let's imagine you had a database driver</p>
  
  <pre><code>var cursor = db.table("my-table").map(function (row) {
    return ["foo", row.foo]
  })
  </code></pre>
  
  <p>You want to determine at run-time what the function is and convert it into an AST format so that you can use your efficient query builder to convert it into SQL or whatever query engine your database has. </p>
  
  <p>This means you don't have to write:</p>
  
  <pre><code>var cursor = db.table("my-table").map(function (rowQueryObject) {
      return db.createArray(db.StringConstant("foo"), rowQueryObject.getProperty("foo"))
  })
  </code></pre>
  
  <p>Which is a function the DB library can execute with a query object and have you build the query object transformation without verbose methods.</p>