Created
January 11, 2019 19:31
-
-
Save ntreu14/788d185e417eece2a3a8c6227a6f54fa to your computer and use it in GitHub Desktop.
Returns leaf nodes from a tree where the elements return true for a given predicate
This file contains 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 'a Node = Group of 'a Node list | Leaf of 'a | |
let tree = Group [ Group [Leaf 1; Leaf 2; Leaf 3]; Group [Leaf 6]; Leaf 9; Leaf 10 ] | |
let isEven n = n % 2 = 0 | |
let flip f a b = f b a | |
let (>>=) = flip List.collect | |
let rec collectLeavesBy predicate = function | |
| Group xs -> xs >>= (collectLeavesBy predicate) | |
| Leaf x -> if predicate x then [Leaf x] else [] | |
collectLeavesBy isEven tree |> printfn "%A" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment