How to apply a function to a variant?

Let these types =

type intC = int;;
type boolC = bool;
type stringC = string;;

type component = A of intC | B of boolC | C of stringC;;

If I want to apply a function to type a of component A, do I need to systematically deconstruct the component?

for example, I have to do:

let add comp =
  match comp with 
   | A i -> Some (i + 2) (*only A interests me, I return i + 2*)
   | _ -> None           (*otherwise I return nothing*)

and then for any function on component A? Is there any way to avoid redundancy?

+5
source share
2 answers

Actually depends on what operation you will perform on your types.

The solution given by @nlucaroni is fine, but if you want to do something more general (and complicated), you can use the entry to store your partial map functions:

type 'a component_m = {
  a : intC  -> 'a;
  b : boolC -> 'a;
  c : stringC -> 'a;
}

let map_component m = function
  | A a -> m.a a
  | B b -> m.b b
  | C c -> m.c c

let add = map_component {
  a = (fun x -> Some (x + 2)); 
  b = (fun _ -> None);
  c = (fun _ -> None);
}

If you do not want to write a function every time (fun _ -> None), you can also use the default value that you extend:

let none = {
  a = (fun _ -> None);
  b = (fun _ -> None);
  c = (fun _ -> None);
}

let add = map_component { none with a = fun x -> Some (x+2) }

, , , .

+4

, ,

let apply_if_a f = function
   | A i          -> Some (f i)
   | (B _ | C _)  -> None

:

val apply_if_a : (int -> 'a) -> component -> 'a option

, , A. , , _, .

+3

All Articles