Skip to content

Instantly share code, notes, and snippets.

@brianberns
Created April 1, 2021 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianberns/fff0a0ff252d39bcdc1cba048b7da027 to your computer and use it in GitHub Desktop.
Save brianberns/fff0a0ff252d39bcdc1cba048b7da027 to your computer and use it in GitHub Desktop.
Rose trees, continuation-passing style
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