Реализация полиномиальных операций в F # - PullRequest
0 голосов
/ 31 декабря 2018

Мне даны типы полиномов и термин, определенный следующим образом: я хочу иметь функцию, которая добавляет термин к полиному и сохраняет термины, с определенной степенью k, меньшей или равной 1. Я подумал, что должен создатьфункция для объединения терминов с одинаковой степенью и использовать ее в функции addTermToPolynomial, вот что у меня есть:

type poly=Poly of (float*int) list
type term = Term of float *int
exception EmptyList

let rec mergeCommonTerm(p:poly)=
    match p with
    |Poly [] -> Poly []
    |Poly (a::af)-> match mergeCommonTerm (Poly af) with 
                    |Poly recursivep -> 


let rec addTermToPoly (x:term, p:poly)=
    match x with
    |Term (coe, deg)-> match p with
                       |Poly[] ->  Poly [(coe,deg)]
                       |Poly (a::af)-> if snd a=deg then Poly ((fst a+coe,deg)::af)
                                       else match addTermToPoly (x,Poly af) with
                                         |Poly recusivep-> mergeCommonTerm(a::recusivep)

Я не знаю, как завершить функцию mergeCommonTerm, потому что я не знаю, какитерации по списку, как двойной цикл.Пожалуйста, помогите мне написать функцию слияния как термин.

1 Ответ

0 голосов
/ 01 января 2019

Типы 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...