Created
July 13, 2024 09:46
-
-
Save arialdomartini/d272d6383e69320aaf750285bff04295 to your computer and use it in GitHub Desktop.
index.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let tree = Node(Leaf "one", Node(Leaf "two", Leaf "three")) | |
type WithCount<'v> = WithCount of (int -> 'v * int) | |
let build l r = Node(l, r) | |
let run (WithCount f) (count: int)= f count | |
let pure' v = WithCount (fun count -> (v, count)) | |
let (<*>) f a = | |
WithCount (fun count -> | |
let fv, fc = run f count | |
let av, ac = run a fc | |
let b = fv av | |
b, ac) | |
let putCount c = WithCount (fun _ -> (), c) | |
let getCount = WithCount (fun c -> c, c) | |
let buildLeaf v count put = | |
let leaf = Leaf (v, count) | |
put (count + 1) |> ignore | |
leaf | |
let rec index<'a> = | |
function | |
| Leaf v -> | |
pure' buildLeaf <*> (pure' v) <*> getCount <*> pure' putCount | |
| Node(l, r) -> | |
pure' build <*> index l <*> index r | |
[<Fact>] | |
let ``indexes a tree`` () = | |
let withCount = index tree | |
let indexed, _ = run withCount 1 | |
test <@ indexed = Node(Leaf("one", 1), Node(Leaf("two", 2), Leaf("three", 3))) @> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment