带表达式的F#类型定义

编程入门 行业动态 更新时间:2024-10-22 10:35:15
本文介绍了带表达式的F#类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以表达以下内容:

Is it possible to express something like this:

type id = int > 0

我知道它不可能静态执行,因为这将意味着F#具有依赖类型.在C#中,我习惯于使用代码协定来执行此类操作并获得运行时强制.我正在这里寻找类似的东西.

I know its not possible to do statically, since this would mean F# has dependent types. In C# I'm used to do this sort of thing with code contracts and get a runtime enforcement. I'm looking for something similiar here.

谢谢

感谢您提供所有利弊的答案.在常规情况下,我只使用F#的一小部分,这是ocaml核心的一个子集,可以很容易地对证明进行编程.所以没有课程.

Thank you for all the answers which have various pros and cons. At the monent I'm only using a small subset of F#, a subset of the ocaml core that lends itself easily to program proofs. So no classes.

推荐答案

与其他人所说的相反,如果我正确理解了您的问题,我建议不要在这里使用类. 由于该值是不可变,因此我们只需要应用一次约束.任何包装器类都将是开销和负载GC.取而代之的是,一个简单的函数可以完成这项工作:

Contrary to what others said, I would suggest not using classes here, if I understood your problem correctly. Since the value is immutable, we need applying constraint only once. Any wrapper classes would be an overhead and load GC. Instead, a simple function will do the job:

let inline constrained predicate errormessage value = if not (predicate value) then invalidArg "value" errormessage else value let positive = constrained (fun x -> x > 0) "Value must be positive" let int1 = positive 5 // OK let int2 = positive -3 // ArgumentException

您可以对其他类型执行相同操作:

You can do the same for other types:

let mustBeLong = constrained (fun (x:string) -> x.Length > 3) "String must be long" let str1 = mustBeLong "foobar" // OK let str2 = mustBeLong "baz" // ArgumentException

在结构中使用相同的内容

Using the same within a struct:

type Point2D = struct val X: int val Y: int new(x: int, y: int) = { X = positive x; Y = positive y } end let point1 = Point2D(5, 3) // OK let point2 = Point2D(5, -2) // ArgumentException

更多推荐

带表达式的F#类型定义

本文发布于:2023-11-17 03:08:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   定义   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!