F # Shortening pattern matching on a tree

Not sure if this is the right place for this question, but I have a function that I'm sure can be simplified, but I'm not sure how to do this.

let rec probOK = function
| Branch(ds, p, Leaf l1, Leaf l2) when p <= 1.0 && p >= 0.0     ->  true
| Branch(ds, p, b1, b2)           when p <= 1.0 && p >= 0.0     ->  probOK b1 && probOK b2
| Branch(ds, p , b1, Leaf l1)     when p <= 1.0 && p >= 0.0     ->  probOK b1
| Branch(ds, p , Leaf l2, b2)     when p <= 1.0 && p >= 0.0     ->  probOK b2
| _                                                             ->  false   

The task is to determine the function that takes probability tree(see below) and check if it satisfies that each probability pis equal 0 <= p <= 1. A probability treehas type

type ProbTree = | Branch of string * float * ProbTree * ProbTree
                | Leaf of string

What it means probability treeis a tree for representing sample spaces of sequential processes, where the results at each stage of the process are either successful or unsuccessful.

Example a probability tree, where the hexagonal stamp is selected, and the probability that it >2is equal 2/3, the probability of it <= 2is equal, 1/3and so on:

Probability tree

, , :

let test = Branch(">2",0.67, Branch(">3",0.5, Leaf "A", Leaf "B")
                           , Branch(">3",0.5, Leaf "C", Leaf "D"))

true, p 0 1.

, , , , , , - ([],Leaf _ )-> true, .

?

EDIT1: ( ):

let rec probOK = function
| Branch(ds, p, b1, b2) when p <= 1.0 && p >= 0.0 ->  probOK b1 && probOK b2
| Leaf _                                          ->  true
| _                                               ->  false   
+4
1

, . , , node:

let nodeProbOk = function
| Branch(_, p, _, _)-> p <= 1.0 && p >= 0.0
| Leaf _ -> true

, , :

let rec forAllNodes pred = function
| Branch(_, _, a, b) as branch -> pred branch && forAllNodes pred a && forAllNodes pred b
| Leaf _ as leaf               -> pred leaf

:

test |> forAllNodes nodeProbOk

, , forAllNodes , . , , .

+4

Source: https://habr.com/ru/post/1686952/


All Articles