genericspolymorphismvlang

How to write a generic sample function in V?


I would like to implement a generic sample function for arrays in V. The inspiration for this is base::sample() in R.

A very basic prototype without the replace and prob options of the R function and limited to integer arrays could look like this:

pub fn sample_int(arr[] int, size int) []int {

  mut res := [0].repeat(size)
  for i := 0; i < size; i++ {
    res[i] = arr[rand.next(arr.len)]
  }

  return res

}

Is it possible at the moment to make this function generic to work with all kinds of arrays? How would I implement this?

There is a section about generics in the V documentation, but I was not able to figure it out with this example code. I also searched for examples in the V repo, but I only found ToDo comments where generics are supposed to be implemented in the future.


Solution

  • The docs are very outdated with the progress of V. Here is the code of how to use generics in V with your function. Also join the discord server for discussions and more talks.

    pub fn sample_int<T>(arr[] T, size int) []T {
    
      mut res := [arr[1]].repeat(size)
      for i := 0; i < size; i++ {
        res[i] = arr[rand.next(arr.len)]
      }
    
      return res
    
    }