Ocaml用户定义的类型模式匹配

问题描述 投票:-1回答:1

这是我的类型定义:

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.

我该如何解决?

ocaml
1个回答
0
投票

在这个片段中

List.map
    (fun x -> match x with
    N a -> a
    T b -> b
    )

两种匹配情况的返回类型不同。如果列表中有任何T b元素,则b将是一个字符串,并且编译器不知道没有任何这样的元素。既然你知道没有,你可以通过提供除b以外的东西来解决这个问题。像这样的东西:

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"
    )
© www.soinside.com 2019 - 2024. All rights reserved.