我正在尝试用F#编写一个递归添加多项式的函数。我的多项式可以表示为元组列表。
例如,2x^4 + 3x^2 + x + 5等于[(2.0,4);(3.0,2);(1.0,1);(5.0,0)]
所有的多项式都是正确结构化的(没有相同次数的重复项,除非是零多项式,按照降幂排序,没有空输入列表)。
我在做这件事时遇到了麻烦。以下是我的代码。
我有两个多项式。
当我调用函数时,我的结果是:
例如,2x^4 + 3x^2 + x + 5等于[(2.0,4);(3.0,2);(1.0,1);(5.0,0)]
所有的多项式都是正确结构化的(没有相同次数的重复项,除非是零多项式,按照降幂排序,没有空输入列表)。
我在做这件事时遇到了麻烦。以下是我的代码。
type term = float * int
type poly = term list
let rec atp(t:term,p:poly):poly =
match p with
| [] -> []
| (a, b) :: tail -> if snd t = b then (fst t + a, b) :: [] elif snd t > b then t :: [] else ([]) :: atp(t, tail)
(* val atp : t:term * p:poly -> poly *)
let rec addpolys(p1:poly,p2:poly):poly =
match p1 with
| [] -> []
| (a,b) :: tail -> atp((a,b), p2) @ addpolys(tail, p2)
我有两个多项式。
val p2 : poly = [(4.5, 7); (3.0, 4); (10.5, 3); (2.25, 2)]
val p1 : poly = [(3.0, 5); (2.0, 2); (7.0, 1); (1.5, 0)]
当我调用函数时,我的结果是:
val p4 : poly =
[(4.5, 7); (3.0, 5); (3.0, 4); (3.0, 5); (10.5, 3); (3.0, 5); (4.25, 2)]
当正确答案为
[(4.5, 7); (3.0, 5); (3.0, 4); (10.5, 3); (4.25, 2); (7.0, 1); (1.5, 0)]