【发布时间】:2012-01-16 18:34:06
【问题描述】:
我对 F# 中的默认“=”(等于)运算符有疑问。它允许比较用户定义的联合类型。问题是:它的复杂性是什么?例如,让我们考虑以下类型:
type Tree<'a> =
| Nil
| Leaf of 'a
| Node of Tree<'a> * Tree<'a>
和以下树:
let a : Tree<int> = Node (Node (Node (Leaf 1, Leaf 2), Node (Leaf 3, Node (Leaf 4, Leaf 5))), Node (Leaf 6, Nil))
let b : Tree<int> = Node (Node (Node (Leaf 1, Leaf 2), Node (Leaf 3, Node (Leaf 4, Leaf 5))), Node (Leaf 6, Nil))
let c : Tree<int> = Node (Node (Node (Leaf 1, Leaf 2), Nil), Node (Node (Leaf 3, Node (Leaf 4, Leaf 5)), Leaf 6))
很明显,这段代码:
printfn "a = b: %b" (a = b)
printfn "a = c: %b" (a = c)
printfn "a = a: %b" (a = a)
产生这个输出:
a = b: true
a = c: false
a = a: true
我希望“a = b”和“a = c”比较需要线性时间。但是“a = a”呢?如果它是恒定的,那么更复杂的结构呢,比如那个:
let d : Tree<int> = Node (a, c)
let e : Tree<int> = Node (a, c)
它会遍历整个 d 和 e 结构还是会停在“a = a”和“c = c”?
【问题讨论】:
标签: f# complexity-theory equals operator-keyword user-defined-types