cod*_*nk1 5 ocaml functional-programming
让这个类型=
type intC = int;;
type boolC = bool;
type stringC = string;;
type component = A of intC | B of boolC | C of stringC;;
Run Code Online (Sandbox Code Playgroud)
如果我想在组件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*)
Run Code Online (Sandbox Code Playgroud)
然后对组件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);
}
Run Code Online (Sandbox Code Playgroud)
如果您不想(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) }
Run Code Online (Sandbox Code Playgroud)
你可以用函子做同样的事情,但在我看来这有点矫枉过正了。