编写一个函数的总和函数 [英] Writing a function that is sum of functions
问题描述
我有以下练习:
编写一个函数,它将成为函数列表的总和。
所以我认为这意味着如果一个函数获得函数列表[f(x); g x); h(x); ...]它必须返回一个函数f(x)+ g(x)+ h(x)+ ...
<
let f_sum(p)我想要做一般情况下的代码,以下是我想到的: h :: t)= fold_left(fun ah - >(fun x - >(hx)+(ax)))ht ;;
问题是我使用+运算符,这意味着它只能在列表中工作具有类型的功能
'a - > int
所以,它可以做得更一般,我的意思是我们可以写一个函数,是列表中给出的('a - >'b)函数的总和吗?是的,你可以加上函数作为你的函数的参数,比如
let f_sum加上fs =
let(+)= plus in
与
|匹配fs [] - > invalid_argf_sum:空列表
| f :: fs - > fold_left ...
您可以推广更多,并要求用户提供零
值,以便您可以返回一个函数,如果列表为空,则返回零。你也可以使用记录对函数进行分组,甚至可以将第一类模块分组(比如,在Core库中的 Commutative_group.S
)。
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?
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).
这篇关于编写一个函数的总和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!