---------------------------------------------------------------------- module CoeffPoly where ---------------------------------------------------------------------- -- COMP2600 -- Assignment 1, 2003 -- Modified by Joseph Curtis (3952239) -- Represent a polynomial as a list of coefficients, such that the -- exponent of each term corresponds to the list index of each component. type Coeff = Float type Expon = Int type Poly = [Coeff] ---------------------------------------------------------------------- add :: Poly -> Poly -> Poly add [] [] = [] add x [] = x add [] y = y add (x:xs) (y:ys) | sum xs + sum ys == 0 = [] -- if the rest of both lists contains -- only zeroes then just output the -- empty list. This takes care of -- having trailing zeroes thus putting -- it in normal form. | otherwise = (x+y):add (xs) (ys) -- adds the two current list items -- together and joins this to the -- list recursivly returned by the -- adding of the rest of the polys. ---------------------------------------------------------------------- sub :: Poly -> Poly -> Poly sub [] [] = [] sub x [] = x sub [] y = map ((-) 0) y sub (x:xs) (y:ys) = (x-y):sub (xs) (ys) -- very similar to the addition -- function. See above. ---------------------------------------------------------------------- eval :: Float -> Poly -> Float eval x [] = 0 eval x ys = ((last ys) * (x ^ fromInt (length (ys)-1))) + eval x (init ys) -- Firstly if the set is empty it evaluates to zero. For all other cases -- the evaluation is performed as follows. The last (higest exponent) list -- item is taken and is multiplied by x to the power of the number of items -- in the list minus 1. This gets the correct exponent because the first -- is the zero exponent. Then this product is added to the sum of the rest -- of the recursivly evaluated polynomial. ----------------------------------------------------------------------