summary refs log tree commit diff stats
path: root/tests
diff options
context:
space:
mode:
authorZahary Karadjov <zahary@gmail.com>2017-04-07 19:35:05 +0300
committerZahary Karadjov <zahary@gmail.com>2017-04-07 19:35:05 +0300
commite11b3520ff54387df5016afc075d2a7cc178031b (patch)
tree31f114e3badcbbabf488175f561dbe178fa6cc22 /tests
parentfb3ff64450526f532492c04c6cc02469cfb3d633 (diff)
downloadNim-e11b3520ff54387df5016afc075d2a7cc178031b.tar.gz
fix #5654
Diffstat (limited to 'tests')
-rw-r--r--tests/concepts/trandom_vars.nim42
1 files changed, 42 insertions, 0 deletions
diff --git a/tests/concepts/trandom_vars.nim b/tests/concepts/trandom_vars.nim
new file mode 100644
index 000000000..a236cebad
--- /dev/null
+++ b/tests/concepts/trandom_vars.nim
@@ -0,0 +1,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 future
+
+proc fakeRandom(): Random =
+  result.random = () => 0.5
+
+let x = uniform(1, 10).map((x: float) => 2 * x)
+
+var rng = fakeRandom()
+
+echo rng.sample(x)