I have a list of
type my_sum = {a : type_a} / {b : type_b}
mylist = [{field_only_in_a = "test"} : type_a,{haha=3 ; fsd=4} : type_b]
I want to do that :
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
Like you can see, after the find I’m sure to get something of type_a but on compilation time I get that :
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.
How could I say to the compilator, that I have extract only one type of the sum type and that I have the good type to acces the record… ?
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_mapwhich find a first element matching a certain criteria and maps it (you use this mapping to project frommy_sumto its casetype_a). Below is a fully working code (compiles on its own):If there was no
List.find_mapfunction in the stdlib there would still be a ton of ways to do it. Probably the simplest would be to useList.filter_mapto obtain alist(type_a)and then get its head withList.head_opt.