在F#中实现约束数字类型的习语/实践? [英] Idioms/Practices for Implementing Constrained Numeric Types in F#?

查看:85
本文介绍了在F#中实现约束数字类型的习语/实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设需要一种数字数据类型,其允许值在指定范围内.更具体地说,假设一个人要定义一个最小值为0且最大值为5000的整数类型.这种情况在很多情况下都会出现,例如在对数据库数据类型,XSD数据类型进行建模时. >

在F#中为此类类型建模的最佳方法是什么?在C#中,执行此操作的一种方法是定义一个结构,该结构实现范围检查重载的运算符,格式等.下面介绍了F#中的类似方法: http://tomasp.net/blog/fsharp-custom-numeric. aspx/

虽然我不需要真正的自定义类型,但是我真的不需要.我真正想要的是域受限的现有类型.例如,我希望能够编写类似

的内容

type MyInt = Value of uint16 where Value <= 5000 (pseudocode)

是在F#中做这种事情的捷径吗,还是实现上述博客文章中所述的实现自定义数字类型的最佳方法?

解决方案

您指的是类型理论中所谓的精简类型,正如Daniel所指出的那样,请查找http://tomasp.net/blog/fsharp-custom-numeric.aspx/

I don't really need though a fully-fledged custom type; all I really want is an existing type with a constrained domain. For example, I would like to be able to write something like

type MyInt = Value of uint16 where Value <= 5000 (pseudocode)

Is there a shorthand way to do such a thing in F# or is the best approach to implement a custom numeric type as described in the aforementioned blog post?

解决方案

You're referring to what are called refinement types in type theory, and as pointed out by Daniel, look for F*. But it is a research project.

As far as doing it with F#, in addition to Tomas' post, take a look at the designing with types series.

这篇关于在F#中实现约束数字类型的习语/实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆