Difference between revisions of "Add polynomials"

From HaskellWiki
Jump to navigation Jump to search
m (Entering a person's name not required for polynomial addition ;))
(Numeric Prelude)
Line 38: Line 38:
   
 
</haskell>
 
</haskell>
  +
  +
==See also==
  +
  +
* [[Numeric Prelude]] [http://darcs.haskell.org/numericprelude/src/MathObj/Polynomial.hs]
  +
* HTam [http://darcs.haskell.org/htam/src/Polynomial.hs]
   
 
[[Category:Mathematics]]
 
[[Category:Mathematics]]

Revision as of 14:20, 30 September 2008

Polynomial Algebra

#!/usr/local/bin/runhugs

module Main where

type Poly = [(Int,Int)] 
-- assume sorted by increasing exponent. 
-- data Rational =  (Poly, Poly)


-- an interesting thing to observe: 
-- when adding, the null polynomial is zero. 
-- when multiplying it is one.  This concept emerges implicitly 
-- in these definitions. 

addPoly :: Poly -> Poly -> Poly
addPoly [] ys = ys
addPoly xs [] = xs
addPoly ((a,b):xs) ((c,d):ys)
    | a == c  = ((a,b+d):(addPoly xs ys))
    | a < c = ((a,b):(addPoly xs ((c,d):ys)))
    | a > c = ((c,d):(addPoly ((a,b):xs) ys))

addManyPolys :: [Poly] -> Poly
addManyPolys ps = foldl 0 addPoly ps

multiply :: [Int] -> [Int] -> [Int]
--multiply polynomials together. 
multiply [] ys = ys
multiply xs [] = xs
multiply ((a,b):xs) ((c,d):ys) 


main = do
       putStr $ show $ addPoly [(0,1),(2,1)] [(0,1)]

See also