Created
April 1, 2021 21:36
-
-
Save brianberns/fff0a0ff252d39bcdc1cba048b7da027 to your computer and use it in GitHub Desktop.
Rose trees, continuation-passing style
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
type ContinuationMonad() = | |
member __.Bind(m, f) = fun c -> m (fun a -> f a c) | |
member __.Return(x) = fun k -> k x | |
let cont = ContinuationMonad() | |
let rec reduce fs = | |
cont { | |
match fs with | |
| [] -> return [] | |
| head :: tail -> | |
let! result = head | |
let! results = reduce tail | |
return result :: results | |
} | |
type 'a Tree = Node of 'a * 'a Tree list | |
let leaf a = Node (a, []) | |
let rec findMax (Node (i, chld)) = | |
cont { | |
let! maxVals = chld |> List.map findMax |> reduce | |
return List.max (i :: maxVals) | |
} | |
[<EntryPoint>] | |
let main argv = | |
let t = Node (1, [ leaf 2; leaf 3 ]) | |
findMax t (printfn "%A") // will be 3 | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment