我注意到我无法使用相同的选项创建两个活动模式,但是我可以在没有任何警告的情况下创建两个具有相似模式的活动模式:
let (|A|B|C|) c =
if (c = 'a') then A
else if (c = 'b') then B
else C
let (|A|B|D|) c =
if (c = '1') then A
else if (c = '2') then B
else D
因此,当以这种方式匹配时:
let check myvar =
match myvar with
| A -> printf "match A\n"
| n -> printf "match other %A\n" n
有时候是这样的:
check 'x' // match other 'x'
check 'a' // match other 'a' !!
check '1' // match A
我有点担心会无意中覆盖现有的活动模式选项,例如,在同一单词可能因不同的语义上下文(如(|Direct|Indirect|)
(路线)和(|Alternating|Direct|)
(当前))而以不同的模式出现的情况下。
如何避免这种情况?
我同意活动模式的阴影处理可能会很棘手-尽管这与歧视工会案例和在F#中记录标签时遇到的问题相同。如果是类型,则始终可以包括类型名称以解决歧义。
如果是活动模式,则可以将它们放在模块中-例如Pat1
和Pat2
:
module Pat1 =
let (|A|B|C|) c =
if (c = 'a') then A
else if (c = 'b') then B
else C
module Pat2 =
let (|A|B|D|) c =
if (c = '1') then A
else if (c = '2') then B
else D
因此,在代码中,您可以使用完全限定的名称,例如Pat1.A
或Pat2.A
:
let check myvar =
match myvar with
| Pat1.A -> printf "match A\n"
| n -> printf "match other %A\n" n
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句