【发布时间】:2016-02-13 06:09:37
【问题描述】:
我正在尝试在 F# 中编写一个递归添加多项式的函数。我的多项式可以表示为元组列表。
例如,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)]
【问题讨论】:
-
您的代码在 FSI 中给了我一个错误:“错误 FS0001:此表达式应具有类型 term,但此处具有类型 'a list。”请提供正确的代码。