如何将函数应用于变体? [英] How applying a function to a variant?
问题描述
让这个类型=
type intC = int ;;
type boolC = bool;
类型stringC = string ;;
type component = intC |的一个B的boolC | C的stringC ;;
如果我想在组件A的类型a上应用函数,是否需要系统地解构组件?
例如,我必须这样做:
让添加comp =
与
|匹配A i - >有些(i + 2)(*只有A感兴趣,我会返回i + 2 *)
| _ - >没有(*否则我什么也没有返回*)
然后对于组件A上的任何函数吗?有没有什么可以避免你的冗余?
它真的取决于你将在你的类型上执行哪种操作。
@nlucaroni给出的解决方案非常好,但如果你想做一些更通用的(和复杂的),你可以使用记录来保存你的局部映射函数:
type'a component_m = {
a:intC - > '一个;
b:boolC - > '一个;
c:stringC - > '一个;
}
让map_component m =函数
| 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 _ - >无);
c =(fun _ - > None);
$ / code $ / pre
如果你不想写(fun _ - > None)
函数,您也可以使用您扩展的默认值:
let none = {
a =(fun _ - > None);
b =(fun _ - >无);
c =(fun _ - > None);
}
let add = map_component {none with a = fun x - >一些(x + 2)}
你可以用函子做同样的事情,但是我认为这个变得矫枉过正。
Let this 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 on the type a of a component A, do I need systematically to deconstruct the component ?
for exemple do 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 a component A ? Is there any mean to avoid thy redundancy ?
解决方案 It really depends which kind of operation you will perform on your types.
The solution given by @nlucaroni is perfectly fine, but if you want to do something a bit more generic (and complex) you can use a record to hold 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 don't want to have to write the (fun _ -> None)
function every time, you can also use a 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) }
You can do the same things with functors but this in my opinion this becomes overkill.
这篇关于如何将函数应用于变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!