没有带有恒定“模板参数"的F#泛型? [英] No F# generics with constant "template arguments"?
问题描述
在我看来,F#泛型似乎不接受常量值作为模板参数".
It just occurred to me, that F# generics do not seem to accept constant values as "template parameters".
假设要创建一个类型RangedInt
,使其表现得像int,但保证仅包含整数值的子范围.
Suppose one wanted to create a type RangedInt
such, that it behaves like an int but is guaranteed to only contain a sub-range of integer values.
一种可能的方法是歧视工会,类似于:
A possible approach could be a discriminated union, similar to:
type RangedInt = | Valid of int | Invalid
但是这也不起作用,因为没有范围信息的类型特定的存储".如果范围也不同,则2个RangedInt实例的类型也应不同.
But this is not working either, as there is no "type specific storage of the range information". And 2 RangedInt instances should be of different type, if the range differs, too.
仍然有点C ++感染,它看起来类似于:
Being still a bit C++ infested it would look similar to:
template<int low,int high>
class RangedInteger { ... };
现在的问题是两个方面:
Now the question, arising is two fold:
- 我是否错过了某些事情,并且存在F#泛型的常量值?
- 如果我没有错过,在F#中完成这样的
RangedInt<int,int>
的惯用方式是什么?
- Did I miss something and constant values for F# generics exist?
- If I did not miss that, what would be the idiomatic way to accomplish such a
RangedInt<int,int>
in F#?
找到了 Tomas Petricek的有关自定义数值类型的博客,相当于我对该博客的提问文章将是:如果他不是一个IntegerZ5
而是一个IntegerZn<int>
自定义类型家族怎么办?
Having found Tomas Petricek's blog about custom numeric types, the equivalent to my question for that blog article would be: What if he did not an IntegerZ5
but an IntegerZn<int>
custom type family?
推荐答案
您请求的语言功能称为从属类型,而F#没有该功能.
The language feature you're requesting is called Dependent Types, and F# doesn't have that feature.
这不是一个特别常见的语言功能,甚至Haskell(大多数其他功能编程语言都仰望"的语言)确实没有它.
It's not a particularly common language feature, and even Haskell (which most other Functional programming languages 'look up to') doesn't really have it.
有 种语言具有依赖类型,但我认为它们都不是主流.我听说最多的可能是 Idris .
There are languages with Dependent Types out there, but none of them I would consider mainstream. Probably the one I hear about the most is Idris.
这篇关于没有带有恒定“模板参数"的F#泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!