为什么内联在这种情况下不起作用?
type TupleBuilder () =
static member inline Cons(a,(b,c)) = (a, b, c)
static member inline Cons(a,(b,c,d)) = (a, b, c, d)
static member inline Cons(a,(b,c,d,e)) = (a, b, c, d, e)
let inline cons h t = TupleBuilder.Cons(h,t)
对TupleBuilder.Cons
的调用给了我以下编译器错误
A unique overload for method 'Cons' could not be determined based on type
information prior to this program point. A type annotation may be needed.
Candidates:
static member TupleBuilder.Cons : a:'a0 * ('a1 * 'a2 * 'a3 * 'a4) -> 'a0 * 'a1 * 'a2 * 'a3 * 'a4,
static member TupleBuilder.Cons : a:'a0 * ('a1 * 'a2 * 'a3) -> 'a0 * 'a1 * 'a2 * 'a3,
static member TupleBuilder.Cons : a:'a0 * ('a1 * 'a2) -> 'a0 * 'a1 * 'a2
答案 0 :(得分:7)
单独内联不会延迟对呼叫站点的过载决策。
您需要在重载调用时添加type A or type B
。
在这种情况下,您可以使用二元运算符轻松完成:
type TupleBuilder () =
static member inline ($) (_:TupleBuilder, (b,c)) = fun a -> (a, b, c)
static member inline ($) (_:TupleBuilder, (b,c,d)) = fun a -> (a, b, c, d)
static member inline ($) (_:TupleBuilder, (b,c,d,e)) = fun a -> (a, b, c, d, e)
let inline cons h t = (TupleBuilder() $ t) h
// val inline cons : h:'a -> t: ^b -> 'c
when (TupleBuilder or ^b) : (static member ( $ ) : TupleBuilder * ^b -> 'a -> 'c)
要获得有关元组的更多内联乐趣,请查看this old blog post。