Rlang-QQ is a way to call the R language interpreter from haskell. This demo shows how to plot things with it, and include those plots in the IHaskell notebook. Ideally this example will become a 4 liner when a new variation of the r quasiquote is written.

In [1]:
{-# LANGUAGE QuasiQuotes #-} -- should enable the extension, but it doesn't for now
:extension QuasiQuotes
import RlangQQ
import IHaskell.Display
In [2]:
let fn = "tmp1" -- should come from a global variable...
let npts = 100 :: Double -- cannot leave out the above let
let sins = map sin [ 2*pi * x / npts | x <- [1 .. npts] ]
     
     
[r| # an R function to make png and svg plots,
    # ideally this part is hidden and we replay plots
    # just like knitr (evaluate package) with code
    # the user does not have to write out
    pp <- function(p) {
        svg(paste0($(fn), ".svg"))
        p()
        dev.off()
        png(paste0($(fn), ".png"))
        p()
        dev.off()
    }

    pp(function() plot( $(sins), type ='l'))
 |]

In [3]:
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Char8 as Char
In [4]:
do
  pp <- B.readFile (fn++".png")
  ps <- hGetContents =<< openBinaryFile (fn++".svg") ReadMode
  length ps `seq` return () -- lazy IO?
  return [png 800 400 (Char.unpack (Base64.encode pp)), svg ps]