[Haskell] randomgen for foreign random functions

Jan-Willem Maessen Janwillem.Maessen at Sun.COM
Fri Jun 25 16:27:59 EDT 2004


On Fri, 2004-06-25 at 12:42, Hal Daume III wrote:
> Hi All --
> 
> Say I have a foreign function:
> 
> foreign import ccall "statistical_c.h gengam"     c_gengam :: CDouble -> CDouble -> IO CDouble
> 
> that returns a random value parameterized by the two CDoubles.  clearly 
> this must happen in IO since the return value will be different each time, 
> and some global state stuff is getting modified on the C side to 
> facilitate future random # generation.
> 
> However, I would like to wrap this into an essentially pure function, ala 
> the Random class.  basically, i want to wrap this up as something like:
> 
> gengam :: RandomGen g => g -> Double -> Double -> (g, Double)
> 
> analogously to the normal random # generation stuff.

You could use an Arbitrary Splittable Supplies library.  See "ioSupply"
on:

http://csg.lcs.mit.edu/~earwig/haskell-lib/index.html


You identify two reasons you need IO here (state and foreign function
call).  Unfortunately, it sounds like they're not so easily separable in
this case (unless you're always passing in the same two Double
arguments, but I suspect you aren't).

So, you could use unsafePerformIO along with the library above, or you
could look at the source code (which also uses unsafePerformIO
internally) and figure out how to poach bits as appropriate.

-Jan-Willem Maessen

> 
> is there a safe way to do this?  one option, of course, is just to 
> unsafePerformIO it and {-# NOINLINE #-} the call, but that is rather, uhm, 
> unsafe, I believe.  it seems to me that something like this should be 
> possible.
> 
> Any thoughts?
> 
>  - Hal
> 



More information about the Haskell mailing list