Ocaml用户定义类型模式匹配
以下是我的类型定义:Ocaml用户定义类型模式匹配,ocaml,Ocaml,以下是我的类型定义: type ('type1, 'type2) symbol = | N of 'type1 | T of 'type2 以下是一些类型: type mysub =| Abc | Bcd | Def 我还有一个列表[N Abc;N Bcd;T”(“] 我想做的是扔掉类型为T的所有项目,同时也扔掉'type1或'type2。因此期望的结果是[Abc;Bcd] 但当我尝试这段代码时: List.map (fun x-> match x with N (a)->
type ('type1, 'type2) symbol =
| N of 'type1
| T of 'type2
以下是一些类型:
type mysub =| Abc | Bcd | Def
我还有一个列表[N Abc;N Bcd;T”(“]
我想做的是扔掉类型为T
的所有项目,同时也扔掉'type1
或'type2
。因此期望的结果是[Abc;Bcd]
但当我尝试这段代码时:
List.map (fun x-> match x with N (a)->a |T (b) ->b ) (List.filter (fun x->match x with
N (type1) ->true |T (type2) -> false) [N Abc;N Bcd; T"("]);;
它给了我以下信息:
Error: This expression has type (mysub, string) symbol list
but an expression was expected of type
(mysub, mysub) symbol list
Type string is not compatible with type mysub.
如何修复它?在此片段中
List.map
(fun x -> match x with
N a -> a
T b -> b
)
两种匹配情况下的返回类型不同。如果列表中有任何tb
元素,则b
将是一个字符串,编译器不知道没有任何此类元素。既然您知道没有,您可以通过提供除b
之外的其他元素作为该情况的结果来解决此问题。S像这样的东西:
List.map
(fun x -> match x with
N a -> a
T _ -> Abc
)
甚至这个:
List.map
(fun x -> match x with
N a -> a
T _ -> failwith "This can't happen"
)
这是一张绷带。正确的解决方案不是使用map和filter的组合,而是更丰富的版本,例如
filter\u map
(('a->'b选项)->'a list->'b list
)或flatmap。