作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
不确定这是否是这个问题的正确位置,但我有一个函数,我很确定可以简化它,但我不确定如何简化。
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
probability tree
的函数。 (见下文)并检查是否满足每个概率
p
是
0 <= p <= 1
.一个
probability tree
有类型
type ProbTree = | Branch of string * float * ProbTree * ProbTree
| Leaf of string
probability tree
是什么意思是表示连续过程的样本空间的树,其中过程中每个阶段的结果要么成功要么失败。
probability tree
的示例,掷出六面骰子的概率是
>2
是
2/3
, 概率是
<= 2
是
1/3
等等:
let test = Branch(">2",0.67, Branch(">3",0.5, Leaf "A", Leaf "B")
, Branch(">3",0.5, Leaf "C", Leaf "D"))
p
在 0 和 1 之间。
([],Leaf _ )-> true
的事情,但我无法完全弄清楚。
let rec probOK = function
| Branch(ds, p, b1, b2) when p <= 1.0 && p >= 0.0 -> probOK b1 && probOK b2
| Leaf _ -> true
| _ -> false
最佳答案
您可以通过将树节点的遍历与对它们的操作分开来简化代码。这是一个检查节点是否有效的函数:
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
用于验证以外的目的。这限制了您需要在代码中使用递归的位置数量,并且应该使事情更容易推理。
关于F# 缩短树上的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46583228/
我是一名优秀的程序员,十分优秀!