I am currently discovering Golang, and I try to implement some random variable generation functions similar to R functions.
To avoid code repetition, I'd like to use inheritance, which is quite complex with Go at first sight.
Each variable implements a x.R() method, which generate a random value following x distribution.
I'd like to implement x.Rn(n int), which simply returns an array of n random values. It is therefore the same for any random variable, as it simply calls x.R() n times.
So far, my implementation is as following:
// Continuouser Implements a continous law
type Continuouser interface{
    R() float64
    D(value float64) float64
    P(value float64) float64
}
// Continuous A Continuous law
type Continuous struct{
    Continuouser
}
// Rn Generate n draws of a continuous random variable
func (c Continuous) Rn(n int) (res []float64){
    if (n < 0){
        panic(errors.New("n must be positive"))
    }
    res = make([]float64,n)
    for i := 0; i < n; i++{
        res[i] = c.R()
    }
    return
}
And here is how I implement a law :
// NewBern Generate a new variable following a Bern(p) law
func NewBern(p float64) (x *Bern){
    x = &Bern{Discrete{},p,1.-p}
    // Discrete.discreter self reference X
    x.Discrete = Discrete{x}
    return
}
// R Generate a random value following the same Bernouilli distribution as x
func (x Bern) R() int64 {
    var u = NewStdUnif()
    // maybe there is a more idomatic way link int(u.R()<p)
    if u.R() < x.p {
        return 1
    }
    return  0
}
So, x does embed an anonymous continuous struct, which in turn embeds a reference to x, that implements the method R().
You can have access to the full repo here on GitHub.
It does work and avoid code redundancy, but is that the idiomatic Golang way?


