是否可以表达以下内容:
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#类型定义
发布评论