Skip to content

Instantly share code, notes, and snippets.

@mfikes
Last active January 22, 2016 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfikes/3433645e09bca86268a5 to your computer and use it in GitHub Desktop.
Save mfikes/3433645e09bca86268a5 to your computer and use it in GitHub Desktop.
eval with function constant

In ClojureScript, evaluating a list that is the application of a function value to an argument.

$ build/Release/planck
cljs.user=> (ns foo.core)
nil
foo.core=> (require '[planck.core :refer [eval]])
nil
foo.core=> (defn square [x] (* x x))
#'foo.core/square
foo.core=> (def do-this (list square 3))
#'foo.core/do-this
foo.core=> (eval do-this)
9
foo.core=> do-this
(#object[foo$core$square "function foo$core$square(x){
return (x * x);
}"] 3)

To do this requires this hack:

(defmethod comp/emit-constant (type (fn []))
  [x]
  (print (s/replace (.-name x) #"\$" ".")))

Here is another example:

foo.core=> ((eval (eval +)) 2 3)
5

But, the hack fails for lambdas:

cljs.user=> (def addition-list (list (fn [a b] (+ a b)) 1 2))
#'cljs.user/addition-list
cljs.user=> (eval addition-list)
Unexpected token '.'
	 eval (NO_SOURCE_FILE)
	 cljs$js$eval_STAR_ (cljs/js.cljs:1196:379)
	 cljs$core$IFn$_invoke$arity$4 (cljs/js.cljs:1274:26)
	 planck$core$eval (planck/core.cljs:1277:54)

The general problem is: Given a function value (a JavaScript object), what do you emit in JavaScript that will evaluate back to the same object?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment