0 people like it.

Extract a given number of randomly selected elements from a list

One of the problems from https://ocaml.org/learn/tutorials/99problems.html

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
open System

let extract list num = 
    let rec pick list num i = 
        match list with
        | h :: t -> 
            if i = num then h
            else pick t num (i + 1)
        | _ -> failwith "error"
    
    let getRandom = 
        let r = Random()
        fun max -> r.Next(1, max + 1)
    
    let rec extractInner list num i = 
        if i = num then []
        else (pick list (getRandom list.Length) 1) :: extractInner list num (i + 1)
    
    extractInner list num 0
namespace System
val extract : list:'a list -> num:int -> 'a list

Full name: Script.extract
Multiple items
val list : 'a list

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val num : int
val pick : ('b list -> int -> int -> 'b)
Multiple items
val list : 'b list

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val i : int
val h : 'b
val t : 'b list
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
val getRandom : (int -> int)
val r : Random
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
Random() : unit
Random(Seed: int) : unit
val max : int
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
val extractInner : ('b list -> int -> int -> 'b list)
property List.Length: int

More information

Link:http://fssnip.net/ro
Posted:2 years ago
Author:Vladimir Khorikov
Tags: ocaml , f#