以下是我定义的活动模式以及尝试进行模式匹配的函数:
let (|Left|) i = i = 0
let (|Top|) j = j = 0
let (|Right|) w i = i = w - 1
let (|Bottom|) h j = j = h - 1
let test w h (i, j) =
match i, j with
| (Left , Top ) -> 1
| (Left , Bottom h) -> 2
| (Right w, Top ) -> 3
| (Right w, Bottom h) -> 4
| (_ , _ ) -> 5
我预计匹配,例如,(0, 0)
与(Left, Top)
和(99, 99)
使用(Right 100, Bottom 100)
。相反,它甚至没有编译(错误之一是“FS0001:该表达式的类型应该为‘bool’,但这里的类型为‘unit’”)。
为此,您需要部分活动模式:
let (|Left|_|) i = if i = 0 then Some Left else None
let (|Top|_|) j = if j = 0 then Some Top else None
let (|Right|_|) w i = if i = w - 1 then Some Right else None
let (|Bottom|_|) h j = if j = h - 1 then Some Bottom else None
let test w h (i, j) =
match i, j with
| (Left , Top ) -> 1
| (Left , Bottom h) -> 2
| (Right w, Top ) -> 3
| (Right w, Bottom h) -> 4
| (_ , _ ) -> 5
test 100 100 (0, 0) |> printfn "%A" // (Left, Top) -> 1
test 100 100 (99, 99) |> printfn "%A" // (Right, Bottom) -> 4
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句