op_Explicit 可以重复吗?

huangapple go评论59阅读模式
英文:

Is repeated op_Explicit possible?

问题

我不确定我要找的东西是否可能,但让我们试试!

我正在尝试定义一个inline函数explicit,它将一个Box<'t>转换成任意层次的't

对于一层 (Box<int> -> int),代码按预期工作,然而 Box<Box<int>> 只转换成了 Box<int>,尽管左边有类型注解。

type Box<'t> =
  {
    Item : 't
  }
  with 
    static member inline op_Explicit (x : Box<'t>) : 't = 
      x.Item

let inline explicit<'t, 'u when 't : (static member op_Explicit : 't -> 'u)> (x : 't) : 'u =
  't.op_Explicit x

let x : int = explicit { Item = 123 }
let y : int = explicit { Item = { Item = 123 } }
let z : int = explicit { Item = { Item = { Item = 123 } } }
英文:

I'm not sure that what I am looking for is possible, but let's try!

I am trying to define an inline function explicit that will convert a Box<'t> into a 't to any level of nesting.

The code works as expected for one level (Box<int> -> int), however Box<Box<int>> is only converted to Box<int>, despite the type-annotation on the L.H.S.

type Box<'t> =
  {
    Item : 't
  }
  with 
    static member inline op_Explicit (x : Box<'t>) : 't = 
      x.Item

let inline explicit<'t, 'u when 't : (static member op_Explicit : 't -> 'u)> (x : 't) : 'u =
  't.op_Explicit x

let x : int = explicit { Item = 123 }
let y : int = explicit { Item = { Item = 123 } }
let z : int = explicit { Item = { Item = { Item = 123 } } }

答案1

得分: 2

我认为简短的答案是否定的。explicit 的签名明确只解开一层,我不认为在 F# 中有任何类型安全的方式来定义你想要的函数。

听起来你实际上希望编译器自动将多个 explicit 调用链接在一起?就其价值而言,C# 将默默地为你插入一个 implicit(不是 explicit)转换,但即使是该语言也不会隐式地链接多个转换。

英文:

I think the short answer is no. The signature of explicit clearly unwraps only a single level, and I don't think there's any type-safe way to define the function you want in F#.

It sounds like you actually want the compiler to automatically chain multiple explicit calls together? For what it's worth, C# will silently insert a single implicit (not explicit) conversion for you, but even that language won't chain more than one together implicitly.

huangapple
  • 本文由 发表于 2023年1月9日 08:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定