1

Assume I have a Frege module

module Util where

total :: [Int] -> Int
total xs = fold (+) 0 xs

If "total" was written in Java, I could call it via

Util.total(Arrays.asList(1,2,3));

What is the best way to call the Frege implementation from Java?

Dierk
  • 1,308
  • 7
  • 13

1 Answers1

2

You could use a good old int [] array, the corresponding frege type would be JArray Int. Because arrays can be made from and into lists in both Java and frege, they are good for such tasks.

Please use the repl to get an idea how to convert the array into a list so that you can pass it to your function.

If there are concerns rgd. heap space, there is also a so called ArrayIterator in Data.Iterators, that is an instance of the ListView type class. So another option would be to write your frege so as to take a ListView

total xs = fold (+) 0 xs.toList

and in java call the equivalent of

ArrayIterator.from (... code to create array here ...)

And if you can't change the frege code, or don't want to, you can make a lazy list with

(ArrayIterator.from (... code to create array here ...)).toList

Last but not least, you can fold over the array without converting it before with foldArray.

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • I’m using Sean Corfield’s Leiningen plug-in to compile Frege code and to be able to call Frege code from Clojure. But when I try to call a Frege function that expects a list of integers (say with `(X/foo [1,2,3])`) I get the error `ClassCastException clojure.lang.PersistentVector cannot be cast to frege.runtime.Lazy`. @Ingo, can the answer above somehow be put to use here as well? – 0dB Dec 19 '15 at 19:21
  • @0dB well, the message is quite clear. I'd put it this way: A clojure list is not a frege list. The answer above is a bit outdated, though. If you can manage to produce a java.util.List, we'll probably find a way to get that data into Frege. It would be good to open up a new question, though. – Ingo Dec 19 '15 at 22:55