Skip to content

Instantly share code, notes, and snippets.

@ntreu14
Created January 11, 2019 19:31
Show Gist options
  • Save ntreu14/788d185e417eece2a3a8c6227a6f54fa to your computer and use it in GitHub Desktop.
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
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