Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Functional programming 使用fold将函数列表合并为单个函数_Functional Programming_Ocaml_Fold - Fatal编程技术网

Functional programming 使用fold将函数列表合并为单个函数

Functional programming 使用fold将函数列表合并为单个函数,functional-programming,ocaml,fold,Functional Programming,Ocaml,Fold,假设我有一个函数列表 let plus_one (x: int) : int = x + 1 in let double (x: int) : int = x * 2 in let square (x: int) : int = x * x in let fun_list = [square, double, plus_one] ;; 使用fold,我想把这个函数列表合并成一个函数。大概 let combined (x: int) : int = x * (2 * (x + 1)) 这就是我

假设我有一个函数列表

let plus_one (x: int) : int = x + 1 in
let double (x: int) : int = x * 2 in
let square (x: int) : int = x * x in
let fun_list = [square, double, plus_one] ;;
使用fold,我想把这个函数列表合并成一个函数。大概

let combined (x: int) : int = x * (2 * (x + 1))
这就是我所拥有的:

let combine_functions (fun_list : ('a -> 'a) list) : ('a -> 'a) =
    List.fold_right (fun f acc -> f acc) fun_list (fun x -> x)
;;

我认为这是可行的,但是当我试着运行它时,它告诉我这个表达式的类型是'a->'a,而它的类型应该是('a->'a)->('a->'a)

我通过将第二行代码从

List.fold_right (fun f acc -> f acc) fun_list (fun x -> x)


我有点不清楚你想要什么样的组合,你的意思是如果是这样的话,那么你的组合函数会是这样的:

square(双倍(加1 x))

((x+1)*2)*((x+1)*2)

这可以通过函数来实现

let combine_functions ls =
  List.fold_right (fun f x -> f x) ls;;
然而,我不完全确定这是否真的是你想要做的。顺便说一句,您不需要显式地键入所有OCaml代码,我个人发现,当我让类型推断为我这样做时,我的工作效率更高

let combine_functions ls =
  List.fold_right (fun f x -> f x) ls;;