Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Types FSharp根据谓词定义类型_Types_F# - Fatal编程技术网

Types FSharp根据谓词定义类型

Types FSharp根据谓词定义类型,types,f#,Types,F#,我的代码看起来像 type U0 = E1|E2|E3... type T2 = {field1: string; field2: string; field3: string} type T1 = T2*T2*T2 type T0 = T1*T1*T1 type P1(x) = (GetUnionCases typeof<U0>).map(fun x -> x.Name).contains(x) 我想对field1的类型强制执行一些谓词P1,该类型field1使得(Get

我的代码看起来像

type U0 = E1|E2|E3...
type T2 = {field1: string; field2: string; field3: string}
type T1 = T2*T2*T2
type T0 = T1*T1*T1
type P1(x) = (GetUnionCases typeof<U0>).map(fun x -> x.Name).contains(x)
我想对
field1
的类型强制执行一些谓词
P1
,该类型
field1
使得
(GetUnionCases typeof).包含(field1)
。我希望这不是太抽象

为此,我想介绍类型P1,定义如下

type U0 = E1|E2|E3...
type T2 = {field1: string; field2: string; field3: string}
type T1 = T2*T2*T2
type T0 = T1*T1*T1
type P1(x) = (GetUnionCases typeof<U0>).map(fun x -> x.Name).contains(x)
type P1(x)=(GetUnionCases typeof).map(fun x->x.Name).contains(x)
一般来说,F#没有任何形式的约束,可以将任意谓词作为约束附加到类型声明中

基于您的抽象示例很难给出更具体的答案,但通常情况下,可以以不同的方式设计域(您的类型),以便通过构造强制执行谓词-换句话说,设计您的类型以使类型的任何值自动满足谓词。有一些实例表明了这一点

我不完全理解您的示例,但假设您希望确保
field1
的字符串包含值
E1
,字符串
field2
包含值
E2
(作为子字符串),依此类推。因此:

{  field1 = "hi E1 there" } // valid
{  field1 = "hi there" } // invalid
您可以将
field1
的类型从
string
更改为
string*string
,表示字符串“E1”的前缀和后缀,因此您只能构造:

{ field1 = "hi", "there" } // valid
现在无法创建不隐式将“E1”作为子字符串的值

我确信我误解了你的例子,但是我希望这能证明这个想法…

你可以考虑和一个命名构造函数一起玩保护级别,就像in一样。