Logo

Programming-Idioms

  • Python
  • Go
import "math/rand"
func pickT(x []T) T {
	return x[rand.Intn(len(x))]
}

Without generics: if you decide to implement pickT, you will have to write it separately for each desired type T.
func pick[T any](x []T) T {
	return x[rand.Intn(len(x))]
}

This generic function works for any type parameter T
import "math/rand"
x[rand.Intn(len(x))]
import random
random.choice(x)
from random import choice
if x: z = choice(x)
with Ada.Numerics.Discrete_Random;
subtype Element_Type is Integer;
type List_Type is array (Positive range <>) of Element_Type;

function Pick_Random (X : List_Type) return Element_Type is
   subtype Index_Range  is Positive range X'Range;
   package Random_Index is new
     Ada.Numerics.Discrete_Random (Index_Range);
   Generator : Random_Index.Generator;
begin
   Random_Index.Reset (Generator);
   return X (Random_Index.Random (Generator));
end Pick_Random;

New implementation...