trandomvars.nim 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. discard """
  2. output: '''
  3. true
  4. true
  5. true
  6. 3
  7. 18.0
  8. 324.0
  9. '''
  10. """
  11. type RNG = object
  12. proc random(rng: var RNG): float = 1.0
  13. type
  14. RandomVar[A] = concept x
  15. var rng: RNG
  16. rng.sample(x) is A
  17. Constant[A] = object
  18. value: A
  19. Uniform = object
  20. a, b: float
  21. ClosureVar[A] = proc(rng: var RNG): A
  22. proc sample[A](rng: var RNG, c: Constant[A]): A = c.value
  23. proc sample(rng: var RNG, u: Uniform): float = u.a + (u.b - u.a) * rng.random()
  24. proc sample[A](rng: var RNG, c: ClosureVar[A]): A = c(rng)
  25. proc constant[A](a: A): Constant[A] = Constant[A](value: a)
  26. proc uniform(a, b: float): Uniform = Uniform(a: a, b: b)
  27. proc lift1[A, B](f: proc(a: A): B, r: RandomVar[A]): ClosureVar[B] =
  28. proc inner(rng: var RNG): B = f(rng.sample(r))
  29. return inner
  30. proc main() =
  31. proc sq(x: float): float = x * x
  32. let
  33. c = constant(3)
  34. u = uniform(2, 18)
  35. t = lift1(sq, u)
  36. var rng: RNG
  37. echo(c is RandomVar[int])
  38. echo(u is RandomVar[float])
  39. echo(t is RandomVar[float])
  40. echo rng.sample(c)
  41. echo rng.sample(u)
  42. echo rng.sample(t)
  43. main()