让这个类型=
type intC = int;;
type boolC = bool;
type stringC = string;;
type component = A of intC | B of boolC | C of stringC;;
如果我想对组件 A 的类型 a 应用函数,我是否需要系统地解构该组件?
例如我必须这样做:
let add comp =
match comp with
| A i -> Some (i + 2) (*only A interests me, I return i + 2*)
| _ -> None (*otherwise I return nothing*)
然后对于组件 A 上的任何函数?有什么办法可以避免裁员吗?
这实际上取决于您将对类型执行哪种操作。
@nlucaroni 给出的解决方案非常好,但是如果您想做一些更通用(和复杂)的事情,您可以使用记录来保存部分映射函数:
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);
}
如果你不想写(fun _ -> None)
每次使用函数时,您还可以使用扩展的默认值:
let none = {
a = (fun _ -> None);
b = (fun _ -> None);
c = (fun _ -> None);
}
let add = map_component { none with a = fun x -> Some (x+2) }
你可以用函子做同样的事情,但在我看来这有点矫枉过正了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)