Skip to content

Instantly share code, notes, and snippets.

@gtrak
Created February 11, 2014 20:45
Show Gist options
  • Save gtrak/8943736 to your computer and use it in GitHub Desktop.
Save gtrak/8943736 to your computer and use it in GitHub Desktop.
;;; JRuby/Clojure fun
(def c (ScriptingContainer. LocalContextScope/SINGLETHREAD LocalVariableBehavior/PERSISTENT))
(defn run
[s]
(. c runScriptlet s))
(def ruby (.getRuntime c))
(defprotocol Conv
(to-ruby [x] "Wrap an object to a ruby object")
(from-ruby [x] "Bring an object back to java"))
(extend-protocol Conv
Number
(to-ruby [x] (org.jruby.RubyFixnum. ruby x))
org.jruby.RubyFixnum
(to-ruby [x] x)
(from-ruby [x] (.getLongValue x)))
(def rb+ (run "Proc.new {|x,y| x+y}"))
(defn ruby-add
([] 0)
([a b]
(-> rb+
(.call (org.jruby.runtime.ThreadContext/newContext ruby)
(into-array [(to-ruby a) (to-ruby b)]))
from-ruby)))
(benchmark (reduce ruby-add 0 (range 10)))
(benchmark (reduce + 0 (range 10)))
(benchmark (reducers/fold 1024 ruby-add ruby-add input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment