# Add polynomials

### From HaskellWiki

(Difference between revisions)

DonStewart (Talk | contribs) (create page for San Jose hackers) |
|||

Line 2: | Line 2: | ||

<haskell> | <haskell> | ||

− | -- | + | #!/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 "Enter a person's name: " | ||

+ | putStr $ show $ addPoly [(0,1),(2,1)] [(0,1)] | ||

fibs = fix $ \f -> 1 : 1 : zipWith (+) f (tail f) | fibs = fix $ \f -> 1 : 1 : zipWith (+) f (tail f) | ||

</haskell> | </haskell> | ||

[[Category:Code]] | [[Category:Code]] |

## Revision as of 05:51, 5 November 2006

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 "Enter a person's name: " putStr $ show $ addPoly [(0,1),(2,1)] [(0,1)] fibs = fix $ \f -> 1 : 1 : zipWith (+) f (tail f)