Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript libraries from Haskell

I am fairly new to Haskell. Recently, I heard about this compiler called GHCJs where you can write code in Haskell which can then be compiled to Javascript.

I am interested in using libraries such as three.js and webgl for making cool interactive 3d animations. Is it possible to call these javascript libraries from Haskell when using GHCJs?

like image 658
smilingbuddha Avatar asked Jul 02 '16 02:07

smilingbuddha


1 Answers

Yes you can call Javascript libraries from ghcjs compiled Haskell.

Here is a simple example:

{-# LANGUAGE JavaScriptFFI      #-}
{-# LANGUAGE OverloadedStrings  #-}

import qualified Data.JSString    as T
import qualified GHCJS.Foreign

foreign import javascript unsafe "alert($1)" alert :: T.JSString -> IO ()

main = alert "hello world"

As you can see from this example, you use the foreign import javascript feature to make JS functions available in your Haskell programs.

I'm not sure if there is an official WebGL interface library, but a quick search around the web shows that others have created partial interface libraries -- e.g. see this example. Basically you have to create the foreign declarations for the functions your application uses.

For three.js, I found this github repo:

https://github.com/manyoo/ghcjs-three

It is also possible to call Haskell code from JS, i.e. see this SO thread:

How to call Haskell from Javascript with GHCJS

like image 71
ErikR Avatar answered Oct 05 '22 13:10

ErikR