Skip to content

Instantly share code, notes, and snippets.

@mmhelloworld
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save mmhelloworld/ae4cb6e01f36c11cd64c to your computer and use it in GitHub Desktop.

Select an option

Save mmhelloworld/ae4cb6e01f36c11cd64c to your computer and use it in GitHub Desktop.
Extending Java classes, implementing interfaces all in Frege without writing Java
module mmhelloworld.hellofrege.HelloWorld where
import mmhelloworld.hellofrege.Script
import Java.Util (List)
-- Implement Runnable interface
newRunnable :: ST s () -> ST s (Mutable s Runnable)
newRunnable action = jsMethod1ST script "Runnable" "create" action where
script =
"var JRunnable = Java.type('java.lang.Runnable'); \n" ++
"var Runnable = (function() { \n" ++
" var clz = Java.extend(JRunnable) \n" ++
" var fns = { \n" ++
" run: function() { \n" ++
" this._lambda.apply(1).result().call(); \n" ++
" } \n" ++
" } \n" ++
" return { \n" ++
" create: function(lambda) { \n" ++
" return new clz() { \n" ++
" _lambda: lambda, \n" ++
" run: fns.run \n" ++
" } \n" ++
" } \n" ++
" } \n" ++
"})(); "
-- Extend java.util.AbstractList with a backed Frege List
fregeListAsJavaList :: [a] -> STMutable s (List a)
fregeListAsJavaList fregeList = jsMethod1ST script "FregeJavaList" "create" fregeList where
script =
"var JAbstractListType = Java.type('java.util.AbstractList'); \n" ++
"var PreludeList = Java.type('frege.prelude.PreludeList'); \n" ++
"var FregeJavaList = (function() { \n" ++
" var AbstractList = Java.extend(JAbstractListType) \n" ++
" var fns = { \n" ++
" get: function(index) { \n" ++
" return PreludeList._excl_excl(this.fregeList, index); \n" ++
" }, \n" ++
" size: function() { \n" ++
" return PreludeList.IListView__lbrack_rbrack.length(this.fregeList); \n" ++
" } \n" ++
" } \n" ++
" return { \n" ++
" create: function(fregeList) { \n" ++
" return new AbstractList() { \n" ++
" fregeList: fregeList, \n" ++
" get: fns.get, \n" ++
" size: fns.size \n" ++
" } \n" ++
" } \n" ++
" } \n" ++
"})(); "
-- Call a Java function: java.lang.Class.getName()
className :: a -> String
className c = jsFn1 script "className" c where
script = "function className(a) { return a.getClass().getName(); }"
main = do
runnable <- newRunnable $ println "Hello World!"
jlist <- fregeListAsJavaList [1,2,3,4,5,6]
element <- jlist.get 3 -- java.util.List.get(index) implemented by `!!` from frege.prelude.PreludeList
Thread.new runnable >>= _.start
println element
println (className jlist) -- jdk.nashorn.javaadapters.java.util.AbstractList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment