0

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?

qiubit
  • 4,708
  • 6
  • 23
  • 37

1 Answers1

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

ivg
  • 34,431
  • 2
  • 35
  • 63