Created
June 14, 2022 07:07
-
-
Save evilz/024cc8984cdda34a9e44cf80ff3634e1 to your computer and use it in GitHub Desktop.
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
// /* | |
// Unival Tree | |
// #1: 5 | |
// 0 | |
// | \ | |
// 0 1 | |
// | \ | |
// 1 0 | |
// | | |
// 1 | |
// |\ | |
// 1 1 | |
// #2: 2 | |
// 0 | |
// | \ | |
// 0 0 | |
// | | |
// 1 | |
// */ | |
type Tree<'a> = | |
| Node of 'a * Tree<'a> list | |
| Leaf of 'a | |
let isUnival tree = | |
let rec inner tree = | |
match tree with | |
| Leaf value -> Result.Ok (1,value) | |
| Node (value,children) -> | |
let allUnival,count = | |
children | |
|> List.map inner | |
|> List.fold (fun (check,total) x -> | |
match x with | |
| Ok (c,v) when v = value -> check, total + c | |
| Ok (c,v) -> false, total + c | |
| Error c -> false, total + c | |
) (true,0) | |
if allUnival | |
then Ok (count + 1, value) | |
else Result.Error count | |
inner tree |> function | |
| Ok (c,v) -> c | |
| Error c -> c | |
Leaf 0 | |
|> isUnival |> printf "%i" | |
Node (0, [Leaf 0]) | |
|> isUnival |> printf "%i" | |
Node (0, [Leaf 0; Leaf 1]) | |
|> isUnival |> printf "%i" | |
Node (0, [ | |
Node (0,[Leaf 0; Leaf 0]) | |
Leaf 1 | |
]) | |
|> isUnival |> printf "%i" | |
Node (0, [ | |
Node (0,[Leaf 0; Leaf 0]) | |
Leaf 0 | |
]) | |
|> isUnival |> printf "%i" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment