How do you return a null Tuple from f# to c#? [duplicate]

*爱你&永不变心* 提交于 2021-02-10 05:04:38

问题


I have this type-correct C# function:

static System.Tuple<int,int> f(int n) { 
  switch (n) { 
    case 0: return null;
    default: return System.Tuple.Create(n,n+1);
  }
}

I try to re-implement it in F#:

let f = function 
| 0 -> null 
| n -> System.Tuple.Create(n, n+1)

Type-checker disagrees, though:

error FS0001: The type '('a * 'b)' does not have 'null' as a proper value.

How do I re-implement the original C# function f in F#?

Note that while this looks like the question “how do I return null in F#” (answer: don’t, use Option) we are asking the slightly different “how do we return null from F# for C# consumers” (can’t use Option, helpful answer below).


回答1:


If you need it to interop with C#, you can use Unchecked.Defaultof like so:

let f = function
    | 0 -> Unchecked.Defaultof<_>
    | n -> (n, n + 1)

However, using null values is strongly discouraged in F#, and if interoperability is not your main concern, using an option is much more natural:

let f = function
    | 0 -> None
    | n -> Some (n, n + 1)


来源:https://stackoverflow.com/questions/65748577/how-do-you-return-a-null-tuple-from-f-to-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!