random.anubis 1.5 KB




read system/string.anubis
read tools/base64.anubis
read tools/string.anubis
read list.anubis

define String 
  _random_string
  (
    Int     size,
    String  current
  )=
  if size = 0 then 
    current
  else
    _random_string( size - 1, current + random(9))
  .
  
  /** generate_random_string
   * generate and return an ASCII readable random string with length of size
   * 
   */ 
public define String
  generate_random_string
  (
    Int size
  ) =
  to_string(extract(base64_encode(to_byte_array(_random_string(size, ""))), 0, size)).
  
      *** (4.6) Randomly shuffling a list. 

         *** (4.6.1) Basic Shuffling
   
define List($T)
  insert_at_position
    (
      Word32    pos, 
      $T        h, 
      List($T)  t
    ) =
  if pos = 0
  then [h . t]
  else if t is 
     {
       [ ] then [h], 
       [a . b] then 
         [a . insert_at_position(pos-1,h,b)]
     }.
   
define List($T)
  random_insert
    (
      $T h,
      List($T) t
    ) =
  with n = truncate_to_Word32(length(t)), 
       r = random(n+1), 
    insert_at_position(r,h,t). 
   
public define List($T)
  shuffle
    (
      List($T) l
    ) =
  if l is
    {
      [ ] then [ ],
      [h . t] then random_insert(h,shuffle(t))
    }.
    
   
         *** (4.6.2) Shuffling a non empty list. 
   
   
 public define NonEmptyList($T)
  shuffle
    (
      NonEmptyList($T) l
    ) =
  if l is [h . t] then 
  if shuffle((List($T))[h . t]) is 
    {
      [ ] then l, // cannot happen
      [h2 . t2] then [h2 . t2]
    }.