module Polynomial where

-- COMP1100 S1, 2006

-- Lab week 5 solution

-- Clem Baker-Finch March 2006
-----------------------------------------------------------------

-- Polynomial Representation
----------------------------

type Poly = [Float]

-- Sum two polynomials
----------------------

-- The patterns for two lists would be:
--   []     []
--   []     (y:ys)
--   (x:xs) []
--   (x:xs) (y:ys)
-- but three is sufficient:

sumPoly :: Poly -> Poly -> Poly
sumPoly [] p2         = p2
sumPoly p1 []         = p1
sumPoly (x:xs) (y:ys) = x+y : sumPoly xs ys

-- Evaluate a polynomial
------------------------

-- I expect this would cause problems if I hadn't given the identity:
-- a0 + a1x + a2x^2 + a3x^3 ...  =  a0 + x*(a1 + x*(a2 + x*(...

-- Make sure they figure out the type of evalPoly first.

-- In lectures I have looked at correspondences between the list
-- structure and the expression we want to evaluate.  In this case, 0
-- corresponds to [] and + "x*(" corresponds to (:) so the definition
-- follows...

-- Stronger students shouls be encouraged to explore other approaches.

evalPoly :: Float -> Poly -> Float
evalPoly x [] = 0
evalPoly x (coeff:coeffs)
    = coeff + x * (evalPoly x coeffs)

-- Sample polynomials for testing
---------------------------------

poly1, poly2, poly3, poly4 :: Poly
poly1 = [1, 7, 5, 2]
poly2 = [42, 2, 1]
poly3 = [-3, 0, 0, 0, 1]
poly4 = [0, -2, 0, 4]

