[Haskell-cafe] R wrapper in haskell

Peng Zhang pczhang at gmail.com
Sun Feb 25 10:22:55 EST 2007

Hi folks,

My primary language is R, which is an imperative functional language. I
start to learn haskell and try to use it instead when a project is
time-consuming and it takes months in R. I like the language very much
so far, but I do miss some important functions in R which can generate
random numbers from all kinds of distributions. R provides a standalone
library in c which contains all these functions and I try to write a
wrapper for haskell. Since I am very new to haskell, I want to hear some
suggestions to confirm that I am on the right track.

The functions are the following:
void set_seed(unsigned int, unsigned int);
void get_seed(unsigned int *, unsigned int *);
they can set or get seed for random number generator.

For any distribution, we have four functions for it
-- Normal distribution
double dnorm4(double x, double mu, double sigma, int give_log)
double pnorm5(double x, double mu, double sigma, int lower_tail,int
double qnorm5(double p, double mu, double sigma, int lower_tail, int
double rnorm(double mu, double sigma)
where dnorm calculates density, pnorm calculates p-value, qnorm
calculates quantile, and rnorm generates normal random variables.

dnorm, pnorm, qnorm are easy since they don't have side-effect. I think
I can just use the following:
foreign import ccall "dnorm4" dnorm :: Double -> Double -> Double-> Int
-> Double
foreign import ccall "pnorm5" pnorm :: Double -> Double -> Double-> Int
-> Int -> Double
foreign import ccall "qnorm5" qnorm :: Double -> Double -> Double-> Int
-> Int -> Double
(Should I use CDouble or CInt here?)

But for rnorm, if I use "foreign import ccall rnorm :: Double -> Double
-> IO Double", then my main function should carry IO monad all the time.
Maybe the better way is that I should "encapsulate" it into a state
monad rng -> (rng, randomnumber). Therefore for rnorm, I should first
write a wrapper in c like
seed2 rnorm_wrapper(seed1, parameters){
and then write another wrapper for rnorm_wrapper in haskell.

Can somebody tell me if this is the right approach? Thank you!


More information about the Haskell-Cafe mailing list