开发者

Tuples in type members using F#

开发者 https://www.devze.com 2023-02-03 14:05 出处:网络
I have a simple question. Why does this not work? type Test1() = member o.toTuple = 1.,2.,3. type Test2() =

I have a simple question. Why does this not work?

type Test1() =
  member o.toTuple = 1.,2.,3.

type Test2() =
  member o.test (x: float, y: float, z: float) = printfn "test"
  member o.test (x: Test1) = o.test x.toTuple

The error is:

Type constraint mismatch. The type float * float * float is not compatible with type Test1 The type 'float * float * float' is not compatible with the type 'Test1'

and

The 开发者_JAVA技巧type 'float * float * float' is not compatible with the type 'Test1'


This doesn't work because the first member test is considered as a multiple argument method in case of overloading. If you need a tupled one, you have to add extra parentheses:

type Test2() =
    member o.test ((x: float, y: float, z: float)) = printfn "test"
    member o.test (x: Test1) = o.test x.toTuple

See explanation of Don Syme here.

Note that if you don't want to add extra parens, you still can deconstruct the tuple and use the multiple argument call:

type Test2() =
    member o.test (x: float, y: float, z: float) = printfn "test"
    member o.test (x: Test1) = let a,b,c = x.toTuple in o.test(a,b,c)


Rename your first method in Type2 to something other than test. You second method is shadowing your first, and thus confusing the compiler.

type Test1() =
   member o.toTuple = 1.,2.,3.

type Test2() =
  member o.print (x: float, y: float, z: float) = printfn "test"
  member o.test (x: Test1) = o.print x.toTuple
0

精彩评论

暂无评论...
验证码 换一张
取 消