Writing a function that is sum of functions

浪尽此生 提交于 2019-12-11 20:11:01

问题


I have the following excercise to do:

Code a function that will be a summation of a list of functions. 

So I think that means that if a function get list of functions [f(x);g(x);h(x);...] it must return a function that is f(x)+g(x)+h(x)+...

I'm trying to do code that up for the general case and here's something I came up with:

let f_sum (h::t) = fold_left (fun a h -> (fun x -> (h x) + (a x))) h t;;

The problem is I'm using "+" operator and that means it works only when in list we have functions of type

'a -> int

So, can it be done more "generally", I mean can we write a function, that is a sum of ('a -> 'b) functions, given in a list?


回答1:


yes, you can make plus function to be a parameter of your function, like

let f_sum plus fs = 
  let (+) = plus in
  match fs with 
  | [] -> invalid_arg "f_sum: empty list"
  | f :: fs -> fold_left ...

You can generalize even more, and ask a user to provide a zero value, so that you can return a function, returning zero if the list is empty. Also you can use records to group functions, or even first class modules (cf., Commutative_group.S in Core library).



来源:https://stackoverflow.com/questions/26935061/writing-a-function-that-is-sum-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!