3

我有一个清单

type my_sum = {a : type_a} / {b : type_b}
mylist = [{field_only_in_a = "test"} : type_a,{haha=3 ; fsd=4} : type_b]

我想这样做:

result = List.find( a -> match a with 
                                      | {a = _} -> true
                                      | _ -> false
                                     end,
                                mylist)
 if Option.is_some(result) then
     Option.some(Option.get(result).field_only_in_a)
 else
     Option.none

正如你所看到的,在找到之后我肯定会得到一些东西,type_a但在编译时我得到了:

    Record has type
{ a : type_a } / { b : type_b }  but field access expected it to have type
{ field_only_in_a: 'a; 'r.a }
Hint:
  You tried to access a sum type with several cases as a record.

我怎么能对编译器说我只提取了一种类型的 sum 类型并且我有好的类型来访问记录...?

4

1 回答 1

4

Well, you cannot really inform the compiler that only a subtype will exist in the list... but you can explicitly create a list with this subtype only. Actually, what you are looking for is List.find_map which find a first element matching a certain criteria and maps it (you use this mapping to project from my_sum to its case type_a). Below is a fully working code (compiles on its own):

type type_a = {fld_a : string}
type type_b = {fld_b : int}
type my_sum = {a : type_a} / {b : type_b}

mylist = [{a = {fld_a = "test"}}, {b = {fld_b = 10}}] : list(my_sum)

get_first_a(l : list(my_sum)) : option(type_a) =
  List.find_map(
    (el -> match el
           | ~{a} -> some(a)
           | _ -> none
    ), l)

_ = prerr("First a-typed element of {mylist} is {get_first_a(mylist)}\n")

If there was no List.find_map function in the stdlib there would still be a ton of ways to do it. Probably the simplest would be to use List.filter_map to obtain a list(type_a) and then get its head with List.head_opt.

于 2011-07-13T15:24:55.993 回答