From dba4ea41ce332f6945e61f580aee675a50a9b237 Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Fri, 7 Jun 2024 13:31:29 +0200 Subject: Some more work on monads --- samples/fun/rng-state.bruijn | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 samples/fun/rng-state.bruijn (limited to 'samples/fun/rng-state.bruijn') diff --git a/samples/fun/rng-state.bruijn b/samples/fun/rng-state.bruijn new file mode 100644 index 0000000..795bad1 --- /dev/null +++ b/samples/fun/rng-state.bruijn @@ -0,0 +1,27 @@ +# MIT License, Copyright (c) 2024 Marvin Borner +# generates three pseudo-random integers using a state monad +# printf | bruijn rng-state.bruijn + +:import std/Combinator . +:import std/String . +:import std/Number . +:import std/Monad/State . + +max (+1000) + +rand [[[0 1 1]] rng] + rng (+1103515245) ⋅ 0 + (+12345) % max + +rand-bool map even? rand + +# accumulating bind (reversed) +triple1 rand >>= (rand >>= (rand >>= [[[[[0 3 [0 3 [0 3 [[0]]]]]]]]])) + +:test ((triple1 (+50) [[1]]) =? (+745)) ([[1]]) + +# normal bind +triple2 rand >>= [rand >>= [rand >>= [[[0 4 [0 4 [0 4 [[0]]]]]]]]] + +:test ((triple2 (+50) [[1]]) =? (+595)) ([[1]]) + +main string→number → triple2 -- cgit v1.2.3