Типы term
и poly
представляют собой Дискриминационные Союзы, используемые в качестве Отчетов.Они могут легко быть развернутыми для использования базового типа (соответственно float * int
и (float * int) list
).Вы можете использовать вспомогательную рекурсивную функцию, чтобы упростить добавление кортежа в список кортежей, соблюдая убывающий порядок градусов.Это также позволяет отдельно управлять исключением EmptyList.
let addTermToPoly (Term (coef,deg), Poly lst) =
let rec loop = function
| [] -> [(coef, deg)]
| (c, d) :: ts ->
if d < deg then (coef, deg) :: lst
elif d = deg then (coef + c, d) :: ts
else (c, d) :: loop ts
if (lst.IsEmpty)
then raise EmptyList
else Poly (loop lst) processed with loop function
Редактировать: добавлены некоторые комментарии к примеру
// Using pattern matching in the function parameters
// allows to directly access to the underlying types
let addTermToPoly (Term (coef,deg), Poly lst) =
// auxiliary function to add a (float * int) tuple
// at the right place in the list
let rec loop = function
// if the list is empty, retun a list containing the tuple
| [] -> [(coef, deg)]
// else, check the value of the head of the list
| (c, d) :: ts ->
// if d is lower than deg, prepend the tuple and return the list
if d < deg then (coef, deg) :: lst
// if d is equal to deg, merge the tuple with the first item and return the list
elif d = deg then (coef + c, d) :: ts
// if d is greater than deg, prepend the first item to
// the result of a recursive call with the tail of the list
else (c, d) :: loop ts
// main function
if (lst.IsEmpty) // if the input lis is empty
then raise EmptyList // then, throw the EmptyList exception
else Poly (loop lst) // else, create a Poly with the list processed with loop function