---------------------------------------------------------------------- module TermPoly where ---------------------------------------------------------------------- -- COMP2600 -- Assignment 1, 2003 -- Modified by Joseph Curtis (3952239) -- Aug 12, 2003 -- Represent a polynomial as a list of terms, where a term is -- represented as a coefficient, exponent pair. Terms with zero -- coefficients do not appear. The terms appear in decreasing -- order of exponent. type Coeff = Float type Expon = Int type Term = (Coeff, Expon) type Poly = [Term] ---------------------------------------------------------------------- add :: Poly -> Poly -> Poly add [] [] = [] -- two empty lists added is the empty list add x [] = x -- an empty list and a non-empty added is just the -- non-empty list add [] y = y add (x:xs) (y:ys) | sum (fst(unzip xs)) + sum(fst(unzip ys)) == 0 = [] | (snd x == snd y) = ((fst x + fst y), snd x):add (xs) (ys) | (snd x > snd y) = x:(add (xs) (y:ys)) | (snd y > snd x) = y:(add (x:xs) (ys)) -- The first guard checks for tuples that evaluate to zero when -- added and if so it returns the empty set. This gets rid of -- zero tuples. The second guard is for when the two exponents -- of the current tuples are the same. These are added together -- and then this is put back into a tuple with the exponent and -- is joined to add recursivle called with the rest of the list. -- The third and fourth guards are essentially the same. If the -- x exponent is larger then there is no y exponent to add the -- coefficient to. Add is recursivly called with x joined to the -- front of it using the rest of the xs list and all of the y:ys -- list. Same as the last guard except for the y exponent being -- greater. ---------------------------------------------------------------------- sub :: Poly -> Poly -> Poly sub [] [] = [] sub x [] = x sub [] y = ((-1 * head(fst (unzip y))), head(snd(unzip y))):(sub [] (tail y)) sub (x:xs) (y:ys) | (snd x == snd y) = ((fst x - fst y), snd x):sub (xs) (ys) | (snd x > snd y) = (x):(sub (xs) (y:ys)) | (snd y > snd x) = ((-1*fst y), snd y):(sub (x:xs) (ys)) -- sub is pretty much the same as add just switched around for subtracting -- instead of adding. ---------------------------------------------------------------------- eval :: Float -> Poly -> Float eval x [] = 0 eval x p = ((head (fst (unzip p))) * (x ^ head (snd (unzip p)))) + (eval x (tail p)) -- If the list is empty it evaluates to zero. -- The list of terms is unzipped so there is a tuple with two lists in it. -- The list of coefficients (first) and the list of exponents (second). -- the head of the coefficients is taken and multiplied by x to the power -- of the head of the exponents. This value is then added to the recursive -- call of add with the same x but the tail of the initial poly. ----------------------------------------------------------------------