module Reflection =
[<RequireQualifiedAccess>]
module Type =
let isType<'a> = Unchecked.defaultof<'a>
let (|IsEqual|Isnt|) (_:'a) (t:Type):Choice<unit,unit> =
let t' = typeof<'a>
if t = t' then IsEqual else Isnt
let (|TypeOf|_|) (_:'a) (t:Type) :unit option =
if t = typeof<'a> then Some ()
else
//printfn "did not match %A to %A" typeof<'a> t
None
open Reflection
match typeof<string> with
// compiles just fine
| Type.TypeOf (Type.isType:int) as x -> Some x.Name
// does not compile
| Type.IsEqual (Type.isType:string) as x -> Some x.Name
| _ -> None
给予Type mismatch. Expecting a Type -> Choice<'a,'b> but given a Type -> 'c -> Choice<unit,unit> The type 'Choice<'a,'b>' does not match the type ''c -> Choice<unit,unit>' (using external F# compiler)
答案 0 :(得分:3)
无论出于何种原因,都只是禁止使用这种模式。只有结果只有一个的模式才能接受其他参数。
这是合法的:
let (|A|) x y = if x = y then 5 else 42
let f (A "foo" a) = printfn "%A" y
f "foo" // Prints "5"
f "bar" // Prints "42"
这是合法的:
let (|B|_|) x y = if x = y then Some (y+5) else None
let f = function
| B 42 x -> printfn "%d" x
| _ -> printfn "try again"
f 42 // prints "47"
f 5 // prints "try again"
但是就是这样。所有其他活动模式必须是无参数的。这两个都是非法的:
let (|A|B|) x y = ...
let (|A|B|_|) x y = ...
如果我不得不猜测,我会说这与可预测的运行时性能有关。当模式匹配或不匹配时,编译器可以为每个参数值精确地运行一次。但是,如果模式返回多个事物,并且其中一些事物存在于match表达式中,而其他事物则不存在,并且并非所有事物都具有相同的参数-找出最佳方法来最小化最小值就变得非常复杂。函数调用量。
答案 1 :(得分:1)
要添加到Fyodor的答案中,spec非常明确地概述了有效的活动模式形式(至少比MSDN还要多)-有关详细信息,请参见第7.2.3节“活动模式”。
五种有效形式为:
(|CaseName|) inp
(|CaseName|_|) inp
(|CaseName1|...|CaseNameN|) inp
(|CaseName|) arg1 ... argn inp
(|CaseName|_|) arg1 ... argn inp
不允许使用其他活动模式功能。
最重要的是,无法将多案例模式与其他参数结合在一起。