避免"Incomplete pattern match"警告的替代方法



我写了一个函数,该函数将数组作为输入,并返回一个相等大小的数组与输出相等的数组。例如:

myFunc [| "apple"; "orange"; "banana" |]
> val it : (string * string) [] =
    [|("red", "sphere"); ("orange", "sphere"); ("yellow", "oblong")|]

现在,我想通过绑定来分配结果。例如:

let [|
        ( appleColor, appleShape );
        ( orangeColor, orangeShape );
        ( bananaColor, bananaShape )
    |] = 
    myFunc [| "apple"; "orange"; "banana" |]

效果很好...

> val orangeShape : string = "sphere"
> val orangeColor : string = "orange"
> val bananaShape : string = "oblong"
> val bananaColor : string = "yellow"
> val appleShape : string = "sphere"
> val appleColor : string = "red"

...除了发出警告外:

warning FS0025: Incomplete pattern matches on this expression. For example, the value '[|_; _; _; _|]' may indicate a case not covered by the pattern(s).

警告的来源和原因已经涵盖,我只是在寻找简洁的工作。此功能调用发生在我功能的顶部附近,我不喜欢将整个功能物体放入比赛中的想法:

let otherFunc =
    match myFunc [| "apple"; "orange"; "banana" |] with
    | [|
        ( appleColor, appleShape );
        ( orangeColor, orangeShape );
        ( bananaColor, bananaShape )
      |] ->
        // ... the rest of my function logic
    | _ -> failwith "Something impossible just happened!"

闻起来很臭。我不喜欢忽略警告的想法 - 反对我更好的判断。还有其他选择对我开放,还是我只需要完全找到其他方法?

如果您期望这种呼叫模式经常使用,那就是制作包装器,以对您期望的元组进行作用,例如

myFunc3 (in1,in2,in3) =
    match myFunc [|in1;in2;in3|] with
    [|out1;out2;out3|] -> out1, out2, out3
    _ -> failwith "Internal error"

等。但是它所做的就是将丑陋的代码移至标准位置,并且写出包装纸会带来不便。

我认为此API没有更好的选择,因为没有办法告诉编译器myFunc总是返回通过它传递的相同数量的元素。

另一个选项可能是用IDisposable类替换myFunc

type MyClass() =
   let expensiveResource = ...

   member this.MyFunc(v) = ...calculate something with v using expensiveResource
   interface IDisposable with
       override this.Dispose() = // cleanup resource

然后将其在

之类的块中使用
use myClass = new MyClass()
let appleColor, appleShape = myClass.MyFunc(apple)
...

适应 @ganesh的答案,这是解决问题的原始方法:

let Tuple2Map f (u, v) 
    = (f u, f v)
let Tuple3Map f (u, v, w) 
    = (f u, f v, f w)
let Tuple4Map f (u, v, w, x) 
    = (f u, f v, f w, f x)

示例:

let Square x = x * x
let (a,b) = Tuple2Map Square (4,6)
// Output:
// val b : int = 36 
// val a : int = 16

,但我猜是这样的更原始的是:

let Square x = x * x
let (a,b) = (Square 4, Square 6)

,如果函数名称太长,例如

// Really wordy way to assign to (a,b)
let FunctionWithLotsOfInput w x y z = w * x * y * z
let (a,b) = 
    (FunctionWithLotsOfInput input1 input2 input3 input4A,
     FunctionWithLotsOfInput input1 input2 input3 input4B)

我们可以定义临时函数

let FunctionWithLotsOfInput w x y z = w * x * y * z
// Partially applied function, temporary function 
let (a,b) =
    let f = (FunctionWithLotsOfInput input1 input2 input3)
    (f input4A, f input4B)

最新更新