【问题标题】:Is there a way to define new type parameters in type constraints with F#?有没有办法用 F# 在类型约束中定义新的类型参数?
【发布时间】:2016-01-14 16:02:03
【问题描述】:

我似乎找不到这样的方法:

type Instance<'Aggregate when 'Aggregate :> Aggregate.T<'State,'Event,'Failure>> = {
  ...
  Aggregate: 'Aggregate
  CurrentState: 'State
  ...
}

请注意,我想:

  • 首先在类型约束中定义类型参数
  • 定义类型时使用类型参数

这当然不会编译,因为'State 没有定义。在保留实例含义的同时,还有其他方法可以做到这一点吗?

我想了一些简单的方法来做到这一点,但它们都失去了意义。例如。 Instance&lt;'State,'Event,'Failure&gt;Instance&lt;'Aggregate&gt; 不太一样。

【问题讨论】:

  • 你必须把类型参数都放在那里:type Instance&lt;'Aggregate, 'State, 'Event, 'Failure when ...&gt;

标签: f# type-constraints


【解决方案1】:

所有类型参数都必须是显式的,所以需要包含'State'Event'Failure

type Instance<'Aggregate,'State,'Event,'Failure when 'Aggregate :> Aggregate.T<'State,'Event,'Failure>> = {
  ...
  Aggregate: 'Aggregate
  CurrentState: 'State
 ...
}

但是,在使用这种类型时,您应该很少需要显式指定那些额外的参数。在创建实例时,编译器应该能够推断出它们,并且即使您必须显式命名 Instance&lt;_,_,_,_&gt; 类型,您也可以为某些参数使用匿名的 _ 占位符。

【讨论】:

  • 是的,我预计会是这样,但我希望我错过了一些聪明的东西。现在我将使用Instance&lt;'State,'Event,'Failure&gt; - 额外的'Aggregate 类型参数感觉有点多余。如果没有更多内容,我会稍后将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多