Derivatives of a polynomial in F#

Just because I was bored…

type Term = {Coefficient: int; Power: int}
type Term = {Coefficient: int; Power: int}
type Polynomial = list<Term>

let derivative polynomial =
    polynomial |> List.map (fun term -> {Coefficient = term.Coefficient * term.Power; Power = term.Power - 1}) |> List.filter (fun x -> x.Power >= 0)

let prettyPrint polynomial =
    let sortedTerms = polynomial |> List.sortBy (fun term -> -term.Power)

    let rec printTerms terms =
        match terms with
        | [] -> ""
        | [term] ->
            match term.Power with
            | 0 -> sprintf "%d" term.Coefficient
            | 1 -> sprintf "%dx" term.Coefficient
            | n -> sprintf "%dx^%d" term.Coefficient term.Power                           
        | h::t -> printTerms [h] + " + " + printTerms t

    printTerms sortedTerms

let sample = [{Coefficient=3; Power=2};{Coefficient=5; Power=1};{Coefficient=4;Power=0}]
let derived = sample |> derivative

printfn "Polynomial:\t%s" <| prettyPrint sample
printfn "Derivative:\t%s" <| prettyPrint derived

 

Leave a comment