gpt4 book ai didi

functional-programming - 如何将函数应用于变体?

转载 作者:行者123 更新时间:2023-12-04 18:12:38 24 4
gpt4 key购买 nike

让这个类型=

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提供的解决方案非常好,但是如果您想做一些更通用(更复杂)的操作,则可以使用一条记录来保存您的部分 map 函数:

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) }

您可以对仿函数执行相同的操作,但是在我看来,这太过分了。

关于functional-programming - 如何将函数应用于变体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com