File: trandomvars2.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (42 lines) | stat: -rw-r--r-- 975 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
discard """
output: "11.0"
"""

type
  # A random number generator
  Random = object
    random: proc(): float
  # A generic typeclass for a random var
  RandomVar[A] = concept x
    var rng: Random
    rng.sample(x) is A
  # A few concrete instances
  Uniform = object
    a, b: float
  ClosureVar[A] = object
    f: proc(rng: var Random): A

# How to sample from various concrete instances
proc sample(rng: var Random, u: Uniform): float = u.a + (u.b - u.a) * rng.random()

proc sample[A](rng: var Random, c: ClosureVar[A]): A = c.f(rng)

proc uniform(a, b: float): Uniform = Uniform(a: a, b: b)

# How to lift a function on values to a function on random variables
proc map[A, B](x: RandomVar[A], f: proc(a: A): B): ClosureVar[B] =
  proc inner(rng: var Random): B =
    f(rng.sample(x))

  result.f = inner

import sugar

proc fakeRandom(): Random =
  result.random = () => 0.5

let x = uniform(1, 10).map((x: float) => 2 * x)

var rng = fakeRandom()

echo rng.sample(x)