Difference between revisions of "Add polynomials"
Jump to navigation
Jump to search
DonStewart (talk | contribs) (create page for San Jose hackers) |
m (Remove the incomplete multiply function) |
||
(6 intermediate revisions by 4 users not shown) | |||
Line 2: | Line 2: | ||
<haskell> |
<haskell> |
||
+ | #!/usr/local/bin/runhugs |
||
− | -- |
||
+ | |||
− | -- example code |
||
+ | module Main where |
||
− | -- |
||
+ | |||
− | fibs = fix $ \f -> 1 : 1 : zipWith (+) f (tail f) |
||
+ | 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 |
||
+ | |||
+ | main = do |
||
+ | putStr $ show $ addPoly [(0,1),(2,1)] [(0,1)] |
||
+ | |||
</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:Code]] |
[[Category:Code]] |
Latest revision as of 05:07, 3 May 2009
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
main = do
putStr $ show $ addPoly [(0,1),(2,1)] [(0,1)]
See also
- Numeric Prelude [1]
- HTam [2]