Logo

Programming-Idioms

  • Scheme
  • C#
using System;
x[new Random().Next(x.Count)]

Consider caching the Random instance, as creating an instance is expensive compared to invoking Next().
using System;
x[Random.Shared.Next(x.Count)]

.NET 6 preview 7 adds a thread-safe global Random instance that reduces the need for custom caching of Random instances.
(list-ref x (random (length x)))

Tested with Chez Scheme
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...