There is now an initial version for Idris 2 - 0.2.1 for the JVM. This is compiled from Idris 2 JVM bootstrap version.
Changes:
Compile initial Idris 2 compiler (0.2.1) with Idris 2 JVM bootstrap version targeting Java 8 bytecode
Add JVM backend
Support primitives such as system, IO, network, clock, buffer etc. for JVM backend
Eliminate tail recursion
Add debug information such as variable name, file name and line number in bytecode from Idris source
Compile Idris modules to Java classes at the bytecode level, Idris top level functions to static Java methods and Idris lambdas into Java lambdas with invokedynamic implementing Java Function interface.
Generate bytecode concurrently for modules
Generate classes with toString and property getters for Idris constructors
I am excited to announce that Idris 2 bootstrap compiler can now run on the JVM along with a JVM backend. Here is a REPL session:
123456789101112131415161718
$idris2__________/_/___//____(_)____|__\///__/___//___/__//Version0.1.1-786152de1_////_////(__)/__/https://www.idris-lang.org/___/\__,_/_//_/____//____/Type:?forhelp[BOOTSTRAPVERSION:Nolongerdeveloped,exceptasabootstrappingstep.]WelcometoIdris2ontheJVM(PrivateBuildOpenJDK64-BitServerVM,1.8.0_275).Enjoyyourself!Main>"hello world""hello world"Main>take10[25..][25,26,27,28,29,30,31,32,33,34]Main>:tmapPrelude.map:Functorf=>(a->b)->fa->fbMain>:execprintLn"Hello Idris 2 on the JVM - this is printed from executing JVM bytecode from memory""Hello Idris 2 on the JVM - this is printed from executing JVM bytecode from memory"Main>
You may notice that the banner includes the JVM version that the Idris compiler is running on. Idris 2 for JVM can run on Java 8 or above. Since the compiler itself runs on the JVM, the last :exec command at line 16 above can directly interpret the generated bytecode on the compiler JVM, and the generated bytecode is loaded from memory without any file system footprint.
Add idris2-boot-jvm/bin from extracted directory to PATH
Run idris2. That’s all!
Features
Eliminate tail recursion using JVM’s GOTO
Trampoline non-self tail calls
Support file, directory, array, IORef and buffer primitives.
Analyse function dependencies to generate bytecode for only used functions from main
Limited type inference on Idris IR to avoid boxing and typecasting in the generated bytecode
Static and instance Java FFI method calls.
Debug information (Idris source file and line numbers) in the bytecode from Idris IR
Currently, the goal for this bootstrap compiler is to be able to compile current Idris 2 so the items here could definitely be improved a lot and other features may be added to support the absolute minimum for building Idris 2.
moduleMainimportSystem.FFI-- Tail call is eliminated with GOTOsum:Int->Intsumn=go0nwherego:Int->Int->Intgoacc0=accgoaccn=go(acc+n)(n-1)mutual-- Mutually recursive functions are trampolined-- keeping it simple with int instead of Nat which is compiled to Java BigIntegerisOdd:Int->BoolisOdd0=FalseisOddn=isEven(n-1)isEven:Int->BoolisEven0=TrueisEvenn=isOdd(n-1)-- Java instance method calls%foreignjvm"java/lang/String"".length"jvmStringLength:String->Int-- Java static method calls%foreignjvm"java/lang/Integer""toBinaryString"intToBinaryString:Int->Stringmain:IO()main=doprintLn$sum5000printLn$isEven100000printLn$intToBinaryString512printLn$jvmStringLength"hello"
Compile
1
idris2Main.idr-omain
The classes will be compiled into build/exec/main_app.
It compiles down to three main modules Main, Prelude and PrimIO. Rest of the classes are data classes for Idris constructors like Just, Nothing, Nil, :: etc.
Run
12345
$ java -cp /path/to/idris2-boot-jvm/lib/runtime-1.0-SNAPSHOT.jar:build/exec/main_app Main
12502500
True
"1000000000"
5
The above example demonstrates tail recursion, mutual recursion, Java FFI instance and static method calls.
sum a tail recursive function, would be compiled into a loop. Here is the decompiled code for the nested go function inside sum:
As we can see here, the tail recursive function call is removed in the default block instead the arguments are updated for next iteration. The loop would continue to run until the base case is reached where the result is returned.
For isEven and isOdd, the tail calls would be trampolined using JVM’s invokedynamic. Here is the decompiled bytecode.
Here since the tail call is not to itself, function call is turned into a thunk which would be eventually unwrapped in a loop.
Now let’s look at FFI calls in the above example. jvmStringLength function is an example for Java FFI instance method call. It calls length function on Java’s java.lang.String instance. Similarly intToBinaryString calls toBinaryString static function on class java.lang.Integer. Function name starting with a dot denotes an instance method call differentiating it from a static method call. Precise types can also be passed explicitly as in the example below with argument types and return type (full code here).
Next step would be to use this bootstrap version to compile current Idris 2 and then porting the JVM backend from here which is on Idris 1 to Idris 2 so there are some interesting things ahead to work on. Meanwhile, if anyone gets a chance to use this boostrap JVM version, please share any feedback or any issues here that can help while we try to compile mainstream Idris 2 for the JVM. Thank you for reading and happy coding!
Here since the Idris compiler doesn’t know anything about Java’s Integer class or its parseInt method, we have to
explicitly provide the function signature. The function call also has the explicit Class
before java/lang/Integer and the type of invocation invokeStatic.
Since we are targeting JVM bytecode, JVM has to know whether a method call is a static method call or an interface
method call or a virtual method call. It would be nice if we don’t have to worry about any of these things and
just call a FFI function with a class name, method name and the arguments. This is the motivation behind this
new feature along with some other nice things like null safety, construtor and method overloading resolution
and exception handling.
Maybe and Either in foreign function calls
Maybe type and Either type can be used in foreign function calls for null safety and exception handling. Maybe
type can be used for argument types and return types. Maybe type used in an argument position will pass null
to the target foreign function if it is Nothing or the actual value if it is Just. Similarly, Maybe type
used for return type will convert null returned from foreign function into Nothing and the non-null value into
Just. At the bytecode level, Maybe wrapper doesn’t exist. It gets compiled down to
null or the actual value.
Either type can only be used in return types to indicate whether the foreign function can throw exceptions.
At runtime, if the foreign function throws exception, it will be captured in the “left” of type Throwable or if the
foreign function completes normally, the result will be stored in the “right” of result type. There are functions try
and catch to handle exceptions which we will see later in the post.
How it works
Before we look at some examples, first let’s declare some class names as we are going to use them in multiple places and
we don’t want to duplicate.
Here jdkimport is just an additional syntax created using Idris syntax extensions. It just calls a type provider
function written in Idris to know about these classes, methods and fields. Note that it imports fields such as
CASE_INSENSITIVE_ORDER, x and also constructors in the name of <init> which is the JVM internal name for
constructors. The jdkimport syntax launches a JVM during compilation without any classpath so it basically can import
all the JDK classes and methods.
There is also another syntax called jvmimport that can take an additional argument, a command, which could be just the
JVM with correct classpath or could be a build tool that properly sets up the classpath from your project dependencies so
that we can “import” classes and methods from external foreign libraries.
Once the information about JVM classes and methods is collected using type provider, appropriate call site, Idris code
similar to the one in the beginning of the post can be created using Idris elaborator reflection with just class name
and member name from the user. As a user, we don’t have to know much about these internals, we just need to import classes
and members and can use them without having to explicitly provide foreign types. Now let’s look at some examples on how we can
actually make FFI calls in the new way.
Here the type of (integerClass <.> "parseInt") is String -> JVM_IO (Either Throwable Int). Since the method can throw
exceptions, it returns an Either. Here we return 0 in case of an exception. Later in the post, we will see a
detailed example of exception handling. As the method returns an Int which is a primitive type in JVM, it cannot be
null and the FFI call already knows that hence the result Int is not wrapped in a Maybe. We don’t provide any
explicit type signature for the foreign function. If we try to pass anything other than String for this foreign
function, it will be a compilation error!
Here we use <.!> with an ! to indicate an unsafe method call instead of <.>. There is also javaUnsafe and java
if you prefer names to operators. The type of (integerClass <.!> "parseInt") is String -> JVM_IO Int.
Sometimes if we are sure that the foreign function would not return null or throw exceptions, we can use unsafe method
calls but as the name indicates, it would fail at runtime if null is returned or an exception is thrown.
3. Overloading resolution
We can pick which overloaded variant we want to use by passing appropriate types to the foreign function and
the FFI call will automatically have corresponding types.
The first function takes an Idris Double and the second function takes Idris Char. The types passed to the foreign
functions to resolve overloading are JVM types.
Safe instance method calls are similar to static method calls except that the instance should be passed as the first
argument. Here again, we don’t provide any explicit type signature or the type of method invocation whether it is static or
instance method but it all works out automatically in a type safe way. Here also we pick a particular overloaded version.
The type of (stringClass <.> "substring(int)") is String -> Int -> JVM_IO (Either Throwable (Maybe String)).
Since the return type is String and it can be null, it is in a Maybe and the method can throw exceptions so the
overall type is in Either.
5. Exception handling
1234567891011121314
dopropValue<-try((systemClass<.>"getProperty(?java/lang/String)")Nothing)[([catchIllegalArgumentExceptionClass,catchNullPointerExceptionClass],\t=>doprintLn"property name is null or empty"pureNothing),([catchNonFatal],\t=>doprintLn"unable to get property value"pureNothing)]printLnpropValue
This example shows how to handle exceptions with different handlers and also shows how to pass a null to a foreign function.
If a FFI function argument type is prefixed with ?, then the idris type would be Maybe nativeTy and we can pass
Nothing to pass a null to the foreign function. We can have handlers for single exception, multiple exceptions or
for all non fatal errors similar to Scala’s
NonFatal.
Similar to methods, constructors can be overloaded and we can select a particular overload variant by explicitly
specifying the foreign type. Constructors can also be invoked in a safe or unsafe way. As constructors cannot return
null, when invoked in a safe way, the result type will only be in Either and not wrapped in a Maybe.
7. Fields
12345678910111213
do-- static field gettercaseInsensitiveComparator<-stringClass<.#!>"CASE_INSENSITIVE_ORDER"printLn!((comparatorClass<.!>"compare")caseInsensitiveComparator"Bar""august")point<-(pointClass<.!>"<init>(int,int)")23-- instance field getterprintLn!((pointClass<.#>"x")point)-- instance field setter(pointClass<.=>"x")point34printLn!((pointClass<.#>"x")point)
Similar to methods and constructors, fields can also be accessed either in a safe or unsafe way using <.#> for safe
getter, <.=> for safe setter, <.#!> for unsafe getter and <.=!> for unsafe setter. Since field access
cannot throw a exception, the return type is automatically just Maybe nativeTy. The field types are automatically
determined without the user having to provide the foreign types of the fields.
Summary
This post demonstrated how with Idris' powerful features FFI, type provider and elaborator reflection, we can safely and
easily access JVM foreign functions. We can access fields, methods and constructors without having to explicitly provide
foreign types and we can access them in safe way without null getting into Idris code and handle exceptions thrown by
foreign functions. It also showed how to call overloaded methods and constructors and how Maybe and Either types are
used with foreign functions.
Idris JVM now helps avoiding nulls getting into Idris from FFI calls using Maybe type.
FFI declarations can have Maybe type in any argument position or in the return type.
The above function is an FFI call to Java’s method
static String getProperty(String key).
The method returns a system property value if the property is set otherwise returns null.
With Maybe type in the Idris function’s return type, the Idris function returns Nothing if the returned value is null
otherwise the value is wrapped in Just.
In the above code, the Java method
JOptionPane.showMessageDialog(parentComponent, message)
takes a nullable parent component and a message. If the parent component is null then the message is displayed in a default frame.
Idris on the JVM! Yes, a dependently typed language on the JVM!
I have been working on a JVM bytecode backend for Idris for the past few months and
it is now at a point that we can even write Android programs with Idris without having to write a single line of Java.
In this post, we will see how Idris works on the JVM and an example Android program written in Idris.
Dependencies are provided as Idris packages, not as Java dependencies like jar or class files.
The overall process is that the compiler reads Idris files and converts them into an intermediate JSON representation and
the JVM bytecode generator takes the JSON files and converts them into JVM bytecode class files directly.
It is only when we run a Java class, we have to provide Java dependency jars. The output option -o represents a directory
where the Java class files will be created.
Why do we have all these classes? We only compiled Main module! This is because Idris performs whole program analysis/compilation
and code generator generates bytecode for all the modules that are relevant for the result produced by the main program.
How does Idris JVM handle tail calls?
Idris JVM eliminates self-recursion with JVM GOTO and uses trampolines for other tail calls.
Let’s look at the following examples.
This program would work just fine without blowing up the stack as it will be compiled down to a loop that uses JVM’s GOTO instruction.
Here is the relevant section from bytecode:
The above code also would work fine without killing the stack. Mutual recursion is handled using trampolines and
the tail calls are delayed and compiled down to Java 8 lambdas. As the bytecode for this is bit long, here is the
decompiled bytecode for the evenT function:
As we can see from the decompiled output above, the oddT call is not performed on the same call stack but a thunk
wrapping the function call is returned using lambda (which is compiled down to JVM’s invokedynamic instruction).
Here is the relevant bit from bytecode for those who are interested:
Java interoperability: Calling Java from Idris and calling Idris from Java
Idris JVM supports calling Java static methods, instance methods, constructors and also accessing static and instance fields from Idris.
At the moment, except for Java arrays, all the Java types can be constructed from Idris and passed to Java methods.
Support for handling nulls and exceptions is currently in progress and will soon be available.
(Update 01/10/2017: We can now
use Maybe type to avoid Java nulls
in Idris code)
To use Idris functions from Java, Idris JVM supports exporting Idris functions as static methods, instance methods,
constructors of an exported Java class. The exported class can also extend a Java class or implement interfaces with Idris functions.
To demonstrate these features, let’s create an Android application In Idris.
moduleMainimportIdrisJvm.IOimportJava.Langpythag:Int->List(Int,Int,Int)pythagmax=[(x,y,z)|z<-[1..max],y<-[1..z],x<-[1..y],x*x+y*y==z*z]IdrisAndroidActivity:TypeIdrisAndroidActivity=JVM_Native$Class"hello/IdrisAndroidActivity"Bundle:TypeBundle=JVM_Native$Class"android/os/Bundle"Context:TypeContext=JVM_Native$Class"android/content/Context"View:TypeView=JVM_Native$Class"android/view/View"TextView:TypeTextView=JVM_Native$Class"android/widget/TextView"InheritsViewTextViewwhere{}CharSequence:TypeCharSequence=JVM_Native$Class"java/lang/CharSequence"InheritsCharSequenceStringwhere{}superOnCreate:IdrisAndroidActivity->Bundle->JVM_IO()superOnCreate=invokeInstance"superOnCreate"(IdrisAndroidActivity->Bundle->JVM_IO())getApplicationContext:IdrisAndroidActivity->JVM_IOContextgetApplicationContext=invokeInstance"getApplicationContext"(IdrisAndroidActivity->JVM_IOContext)newTextView:Context->JVM_IOTextViewnewTextView=FFI.new(Context->JVM_IOTextView)setText:InheritsCharSequencecharSequence=>TextView->charSequence->JVM_IO()setTextthistext=invokeInstance"setText"(TextView->CharSequence->JVM_IO())this(believe_metext)setContentView:InheritsViewview=>IdrisAndroidActivity->view->JVM_IO()setContentViewthisview=invokeInstance"setContentView"(IdrisAndroidActivity->View->JVM_IO())this(believe_meview)onCreate:IdrisAndroidActivity->Bundle->JVM_IO()onCreatethisbundle=dosuperOnCreatethisbundlecontext<-getApplicationContextthistextView<-newTextViewcontextsetTexttextView$"Hello Android from Idris! pythag 50 is "++show(pythag50)setContentViewthistextViewmain:IO()main=pure()androidExport:FFI_ExportFFI_JVM"hello/IdrisAndroidActivity extends android/support/v7/app/AppCompatActivity"[]androidExport=FunsuperOnCreate(Super"onCreate")$FunonCreate(ExportInstance"onCreate")$End
The above program demonstrates calling Java instance methods (setText for example) and constructors (newTextView).
It further demonstrates how to handle inheritance relationship when passing subclass instances to a parent class type.
For example, function setContentView takes a View but we can pass a TextView as it is a subclass of View and we
mention that to Idris via Inherits View TextView where {}.
It also demonstrates how we can create a Java class that extends another class and override methods with Idris functions.
The last section androidExport creates a Java class named hello/IdrisAndroidActivity that extends android/support/v7/app/AppCompatActivity.
The Java class also creates a wrapper method superOnCreate that just delegates to super.OnCreate and the class also overrides onCreate method
with Idris' onCreate function. The Java class can also implement one or more Java interfaces with something like,
Then package the classes compiled above along with idris-jvm-runtime-1.0-SNAPSHOT.jar classes in a single jar and copy into an
android project’s app/libs directory.
Change the activity class name in android manifest file to the Idris exported class name hello.IdrisAndroidActivity.
Then run ./gradlew installDebug from android project after starting an emulator or connected to an android device.
Finally we should see our Idris code running on Android! It should look something like this:
Currently there are 2 ways we can write Haskell on the JVM:
Frege, a language that follows Haskell 2010 standard and compiles to Java.
Haskell itself by compiling it to JavaScript via GHCJS.
Frege is basically a Haskell for the JVM and infact conforms to Haskell 2010 with few inbuilt GHC extensions. Even with good Java interop, it doesn’t sacrifice its type guarantees and currently is the only pure language on the JVM.
In this post, I am going to explore another interesting option: Haskell itself on the JVM. Haskell can be compiled to JavaScript using GHCJS and Java has an inbuilt JavaScript engine, called Nashorn so it is actually possible to compile Haskell to JavaScript and run the resulting JavaScript on the JVM.
Here is a simple Haskell code that can be run on the JVM:
Nashorn doesn’t have an inbuilt console object and Haskell’s putStrLn prints to the console so we have to provide an implementation of console. The implementation, as can be seen from the code above, is actually backed by Java’s System.out.print. That is our first example of calling Java from Haskell. sysexit is another function calling Java. sysexit is needed here as otherwise the program just keeps on running which I think is because of JavaScript event loop or something similar that prevents the JVM from shutting down.
Compiling Haskell with GHCJS and running on JVM
123456
$ ghcjs -o HelloJava HelloJava.hs
[1 of 1] Compiling Main ( HelloJava.hs, HelloJava.js_o )
Linking HelloJava.jsexe (Main)
$ jjs HelloJava.jsexe/all.js
Hello from Haskell!
jjs is a JVM laucher for JavaScript code similar to Node. It is also possible to run this as a regular Java program along with other Java classes without jjs. jjs is just a convenient way to run just JavaScript code on the JVM. Above GHCJS compiles the Haskell code to JavaScript in one file all.js and the JVM runs the JavaScript code from all.js.
Example 2
Now let’s look at another example that shows how to convert between Haskell and Java lists:
Converstion between Haskell and Java Lists (HaskellJavaListsConversion.hs)download
{-# LANGUAGE ForeignFunctionInterface #-}{-# LANGUAGE JavaScriptFFI #-}{-# LANGUAGE UnliftedFFITypes #-}{-# LANGUAGE GHCForeignImportPrim #-}{-# LANGUAGE TypeSynonymInstances #-}{-# LANGUAGE FlexibleInstances #-}{-# LANGUAGE DataKinds #-}{-# LANGUAGE PolyKinds #-}{-# LANGUAGE DeriveDataTypeable #-}{-# LANGUAGE TypeFamilies #-}moduleMainwhereimportControl.Monad.STimportGHCJS.TypesimportGHCJS.ForeignimportGHCJS.PrimimportData.TypeableimportGHC.STdataMutabilityTypes=Mutable|Immutable|STMutablesdataIsItMutable=IsImmutable|IsMutable-- Copied from GHCJS.Internal.Types. Not sure why this is not exposed.typefamilyMutability(a::MutabilityTypes)::IsItMutablewhereMutabilityImmutable=IsImmutableMutabilityMutable=IsMutableMutability(STMutables)=IsMutable{- java.util.ArrayList class and its methods -}newtypeSomeArrayList(a::MutabilityTypes)=SomeArrayListJSValderivingTypeabletypeArrayList=SomeArrayListImmutabletypeMutableArrayList=SomeArrayListMutabletypeSTArrayLists=SomeArrayList(STMutables)instanceIsJSVal(SomeArrayListm)-- ArrayList Constructorforeignimportjavascriptunsafe"new $1()"arrayList_new::JType->STs(STArrayLists)-- Adds an element to ArrayListforeignimportjavascriptunsafe"$2.add($1)"arrayList_add::JSVal->STArrayLists->STs(){- java.util.Iterator class and its methods -}newtypeSomeIterator(a::MutabilityTypes)=SomeIteratorJSValderivingTypeabletypeIterator=SomeIteratorImmutabletypeMutableIterator=SomeIteratorMutabletypeSTIterators=SomeIterator(STMutables)instanceIsJSVal(SomeIteratorm)-- Create an Iterator from an ArrayListforeignimportjavascriptunsafe"$1.iterator()"iterator::STArrayLists->STs(STIterators)foreignimportjavascriptunsafe"$1.hasNext()"iterator_hasNext::STIterators->STsBoolforeignimportjavascriptunsafe"$1.next()"iterator_next::STIterators->STsJSVal{- Other Nashorn imports -}-- Represents a Java typenewtypeJType=JTypeJSValforeignimportjavascriptunsafe"java.lang.System.out.println($1)"jprintln::JSVal->IO()foreignimportjavascriptunsafe"java.lang.System.exit($1)"sysexit::Int->IO()-- Imports a Java classforeignimportjavascriptunsafe"Java.type($1)"jimport::JSVal->JType{- Create an instance of Java's ArrayList from Haskell's list -}listToArrayList::[JSVal]->STs(STArrayLists)listToArrayListxs=doletarrayListClass=jimport$toJSString"java.util.ArrayList"arrList<-arrayList_newarrayListClassgoxsarrListwherego[]arrList=returnarrListgo(x:xs)arrList=doarrayList_addxarrListgoxsarrList{- Create Haskell's list from Java's Iterator -}iteratorToList::STIterators->STs[JSVal]iteratorToListitr=reverse<$>go[]wheregoacc=dohasNext<-iterator_hasNextitrifhasNextthendonext<-iterator_nextitrgo(next:acc)elsereturnacc-- Nashorn doesn't provide default console object. Haskell's putStrLn logs to the console.foreignimportjavascriptunsafe"console={ \ \ log: function(s) { java.lang.System.out.print(s); },\ \ info: function(s) { java.lang.System.out.print(s); },\ \ warn: function(s) { java.lang.System.out.print(s); },\ \ debug: function(s) { java.lang.System.out.print(s); },\ \ error: function(s) { java.lang.System.err.print(s); }\ \ }"setupConsole::IO()demo=runST$dojlist<-listToArrayList.maptoJSInt$[1..5]iteratorjlist>>=iteratorToListmain=dosetupConsolemapM_(putStrLn.show.fromJSInt)demosysexit0
In the code above, two Java types are used: java.util.ArrayList and java.util.Iterator.
Importing a Java class
A Java class can be imported with Java.type(className) Nashorn JavaScript code. Line 80 defines the corresponding Haskell FFI function:
123
-- Imports a Java classforeignimportjavascriptunsafe"Java.type($1)"jimport::JSVal->JType
Creating an instance of a Java class
An instance can be created by invoking the constructor on the Java class with new. Here is the corresponding FFI:
It takes the ArrayList class and invokes the dafault ArrayList constructor to return an instance of it. In the same way, we can create FFI functions for ArrayList.add and ArrayList.iterator to return an Java Iterator instance.
The function listToArrayList takes a Haskell list and return an instance of Java ArrayList. As the java list is mutable, it is returned as STArrayList s inside ST. This function first creates an instance of ArrayList by invoking the Java constructor and then calls ArrayList.add to add items from Haskell list to the ArrayList.
In the similar way, the function iteratorToList takes a Java iterator and returns Haskell list by extracting items from the iterator by invoking corresponding FFI functions for Iterator.hasNext and Iterator.next.
Building with Stack
It is easy to setup a GHCJS project with Stack so that we can add other dependencies easily and build it for GHCJS. With the above code in a stack project “haskell-jvm-hello”, we can build it with stack build and run it with jjs:
Java’s Nashorn JavaScript engine opens up few more ways for the JVM to be polyglot and it is so good to have one of the best languages, Haskell, on the JVM. Actually it should also be possible to run PureScript as well in this way on the JVM but that is for another day. Happy Haskelling!
Frege also provides some shortcuts to apply these functions:
1234567891011
frege>p.x-- Same as `Point.x p`3frege>p.{x=10}-- Same as `Point.{x = } p 10`Point104frege>p.{x<-}-- Same as `Point.{x <-} p`::(Int->Int)->Pointfrege>p.{x<-(+10)}-- Same as `Point.{x <- } p (+10)`Point134
Multiple updates can be combined:
12
frege>p.{x<-(+8),y=20}-- Increment x by 8 and set y to 20Point1120
Accessors and updates can be at any level deep.
Let’s create another type:
Here we have an aggregate type Circle which composes another type Point for it’s field center.
Now we can update and select fields at different levels:
In the latest version, Frege provides syntactic sugar for lambdas using underscores. For example, T.foo can be written
as _.foo if the type can be deduced from the context the lambda is applied. Hence the following two are equivalent.
In the above code, we have two constructors Point2d and Point3d where the field z exists only for Point3d.
We can check for the existence of field z like this:
For more details on how these field existence check, accessor and mutator functions are generated for a record type,
here is the link to Frege language reference: http://www.frege-lang.org/doc/Language.pdf.
modulehellojava.HelloJavawheredataLinkedLista=nativejava.util.LinkedListwherenativeadd::Mutables(LinkedLista)->a->STsBoolnativeget::Mutables(LinkedLista)->Int->STs(Maybea)throwsIndexOutOfBoundsExceptionnativenew::()->STMutables(LinkedLista)fromFregeList::[a]->STMutables(LinkedLista)fromFregeListxs=LinkedList.new()>>=loopxswhereloop(x:xs)jlist=LinkedList.addjlistx>>loopxsjlistloop[]jlist=returnjlistplusTop::Mutables(LinkedListInt)->STs(MaybeInt)plusTopxs=doa<-xs.get0b<-xs.get1return((+)<$>a<*>b)dataIndexOutOfBoundsException=nativejava.lang.IndexOutOfBoundsExceptionderiveExceptionalIndexOutOfBoundsExceptiondataException=nativejava.lang.ExceptionderiveExceptionalExceptiondataNullPointerException=nativejava.lang.NullPointerExceptionderiveExceptionalNullPointerExceptionpurenativeshowThrowabletoString::Throwable->Stringmain_=dojavaList<-LinkedList.fromFregeList[1,2,3]try(\xs->plusTopxs>>=(println.maybe"Got a null pointer"show))javaList`catch`(\(npe::NullPointerException)->println$showThrowablenpe)`catch`(\(exception::Exception)->println$showThrowableexception)
We can observe the following things from the above code:
Making use of a Java class and its methods
Using a Java object in a Frege function
Using Java Exceptions in functions
Handling Java exceptions
1. Making use of a Java class and its methods:
If a Java class is pure then without much effort, we can use that class in Frege. For example,
A Java class is declared with data declaration in Frege. The identifier after the data keyword
is the corresponding type for the Java class in Frege and the qualified Java class is identified after the native
keyword followed by the instance methods, static methods or even some Frege functions not defined in the
original Java class.
An important point here is that the instance methods on BigInteger take Integer as their
first argument which is the this reference on which the methods will be invoked.
Coming back to our original example, here
we are trying to use the mutable Java class java.util.LinkedList.
An obvious difference between this one and the BigInteger example is that the
functions now do not have the pure keyword in front.
The next difference is that the instance methods now cannot take the simple type like LinkedList a as we did for
Integer but the type is now Mutable s (LinkedList a) since it is not a pure function.
If we don’t annotate a native function pure and we don’t use Mutable to consume or return a mutable Object, it will be a
compilation error. Mutable objects can only be used in ST or IO actions so the return type
must be in ST or IO monad.
The LinkedList.add() method returns a boolean. Since
it is an impure function, it should be used in ST monad. Here the boolean itself is pure so it is just ST s Bool.
Take a look at the third function new, LinkedList constructor. This function is impure and it returns
a mutable object, a new LinkedList instance, so the return type is ST s (Mutable s (LinkedList a)) for which the shorthand is STMutable s (LinkedList a).
Here is an example for a native function not being part of a native
data declaration. This is useful when a native class is already
declared in Frege in some module but the function that we are looking
for is missing in the data declaration.
Here showThrowable is the Frege function name for Throwable.toString(). Since it is an
instance method on Throwable, the first argument is of type
Throwable and then the formal arguments' types (in this case, none) and return type.
2. Using a Java object in a Frege function
A native data declaration doesn’t have to just contain the native members, it can also have
additional Frege functions.
In our example, the function fromFregeList is not defined in
the Java class but it has been added as an utility function to create a LinkedList from a frege list.
Here again the same rule as in the previous section applies: To return a mutable Java object,
we should use ST s (Mutable s TheJavaType) which is nothing but STMutable s TheJavaType.
In the same way, the plusTop function takes a mutable Java object so the parameter type is
Mutable s (LinkedList Int). Also since it consumes a mutable type, it must be in ST monad hence
the return type is ST s (Maybe Int) returning an Maybe Int in ST.
3. Using Java Exceptions in functions
To use a Java Exception class, it must be first defined in a Frege
module. It is the same as declaring native declaration for a Java class but
additionally we need to derive the Exceptional type class so that the exception can later be handled with
catch.
The type of catch is Exceptional β => ST γ α -> (β->ST γ α) -> ST γ α.
Here the action is the code where an exception might be thrown
and the handlers handler1 and handler2 take an exception and
return another value in ST monad. The infix notation facilitates
adding multiple handlers with better readability. Further here the
handler1 must be more specific(in terms of the types of the
exceptions being handled) than handler2. Also note that from Frege standard library with respect to catch:
Note If action is of the form:
doSomething arg
then, depending on the strictness of doSomething the argument arg may be evaluated
before the action is returned. Exceptions (i.e. undefined values)
that occur in the construction of the action do not count as
exceptions thrown during execution of it, and hence cannot be catched.
Example:
println (head []) `catch` ....
will not catch the exception that will be thrown when println evaluates
Unlike catch, try takes a function that produces a monadic value. If
the function can throw an exception, it must result in an ST
monad which can then be passed to catch to handle those
exceptions. In our example, \xs -> plusTop xs >>= (println . maybe "Got a null pointer"
show) is the function which when applied to a
java.util.LinkedList might throw a NullPointerException or
IndexOutOfBoundsException:
1234
try(\xs->plusTopxs>>=(println.maybe"Got a null pointer"show))javaListcatch`(\(npe::NullPointerException)->println$showThrowablenpe)catch`(\(exception::Exception)->println$showThrowableexception)
Since the construction of action is deferred through a lambda
here, try eliminates the issue with catch mentioned in the above note.
Extending a class or implementing an interface in Frege:
One thing that is not shown in the example is extending a Java class
or implementing an interface in Frege. Unfortunately both are not possible in Frege
yet. There is a workaround though using a Java class which extends a
class or implements an interface but instead of an implementation on
its own, it just delegates to a Frege function. For example, see
here
for implementing java.lang.Runnable in Frege using a Java class
frege.runtime.SwingSupport which takes a Frege function and then
delegates to it in run method implementation.
This concludes our little experimentation calling Java from Frege. The
other interesting side, calling Frege from Java, is for a
future post.