英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论