Interoperability with Java in Frege, especially in IO Monad

218 Views Asked by At

I would like to translate this java code into Frege Haskell:

    PApplet pApplet = new PApplet();
    System.out.print(pApplet.toString());
    PApplet.runSketch(new String[]{"test"}, pApplet);

I did so far:

data PApplet = mutable native processing.core.PApplet
  where
    native new :: () -> IO PApplet
    native toString :: PApplet -> IO String

native runSketch processing.core.PApplet.runSketch
  :: ArrayOf RealWorld String -> PApplet -> IO ()

main _ = do p <- PApplet.new
            pStr <- p.toString
            putStrLn pStr
            args = JArray.fromList ["test"]
            runSketch args p

Part up to main compiles but then I get those errors:

E Process.fr:14: type error in expression fromList ("test":[])
    type is : STMutable t1 (JArray String)
    expected: ArrayOf RealWorld String
E Process.fr:15: type error in expression p
    type is : IO PApplet
    expected: PApplet
E Process.fr:12: type error in expression >>= p.toString (λpStr -> >> (putStrLn pStr) (runSketch (fromList ("test":[])) p))
    type is : IO ()
    expected: ()→t1
E Process.fr:11: type error in expression λp -> >>= p.toString (λpStr -> >> (putStrLn pStr) (runSketch (fromList ("test":[])) p))
    type is : IO ()
    expected: ()→t1
E Process.fr:11: type error in expression >>= new (λp -> >>= p.toString (λpStr -> >> (putStrLn pStr) (runSketch (fromList ("test":[])) p)))
    type is : ()→t1
    expected: IO ()
E Process.fr:11: type error in expression λ_ -> >>= new (λp -> >>= p.toString (λpStr -> >> (putStrLn pStr) (runSketch (fromList ("test":[])) p)))
    type is : ()→t1
    expected: IO ()
E Process.fr:12: can't find a type for  p.toString `toString`
    is neither an overloaded function nor a member of  IO PApplet

I'm trying hard to meet compiler criteria, but without success. After countless random combinations this snippet above seems the most reasonable to me. Do I need type hints in do block? I don't get why p <- PApplet.new evaluates into IO PApplet? and how to make JArray.fromList to return ArrayOf RealWorld String ? Frege is great but interoperability is quite daunting. Is it possible to have more examples focused on it on Frege github?

1

There are 1 best solutions below

0
On BEST ANSWER

You have

ST s X

and you want

X

and you are in IO, which is nothing but ST RealWorld

So, the most natural solution would be to replce the = with <- in the line

args = JArray.fromList ["test"]

and you're set!

Granted, the whole story is a bit difficult because of the type aliases:

type ArrayOf a x = Mutable a (JArray x)
type STMutable s a = ST s (Mutable s a)

Had the de-aliaser choosen to translate

ST s (Mutable s (JArray String))

back to

ST s (ArrayOf s String)

you probably would have seen it.