Skip to content

Instantly share code, notes, and snippets.

@kashmervil
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save kashmervil/5a49a07d55934d77f131 to your computer and use it in GitHub Desktop.

Select an option

Save kashmervil/5a49a07d55934d77f131 to your computer and use it in GitHub Desktop.
data Polynomnom = P [Int]
instance Show Polynomnom where
show (P polynom) =
let showp (P []) = ""
showp (P xs) = nom ++ showp (P (init xs))
where nom
| x == 0 = ""
| x < 0 = "-" ++ show (abs x) ++ temp
| otherwise = "+" ++ (if (x == 1) then "" else (show (abs x))) ++ temp
where x = last xs
temp
| (x == 1)&&(l == 0) = "1"
| (l == 0)&&(x /= 1) = ""
| (l == 1) = "x"
| otherwise = "x^" ++ show l
where l = length xs - 1 in
case showp (P (polynom)) of "" -> "0"
'+':xs -> xs
xs -> xs
simplify (P p1) = P $ fst $ foldr (\x acc@(xs,flag)-> if flag && x == 0
then acc
else (x:xs,False)) ([],True) p1
instance Eq Polynomnom where
(==) (P p1) (P p2) = (simplify p1) == (simplify p2)
arifm :: (Int -> Int -> Int) -> Polynomnom -> Polynomnom -> Polynomnom
arifm f (P p1) (P p2) = simplify $ P (zipWith f (p1 ++ (take (-degsub) zeros)) (p2 ++ (take degsub zeros)))
where degsub = length p1 - length p2
zeros = repeat 0
instance Num Polynomnom where
(+) = arifm (+)
(-) = arifm (-)
(*) a b = simplify $ helper 0 a b
where
helper :: Int -> Polynomnom -> Polynomnom -> Polynomnom
helper _ _ (P []) = P []
helper c a@(P p1) (P (x:xs)) = P (zeros c ++ (map (*x) p1)) + (helper (c+1) a (P xs))
where zeros x = take x $ repeat 0
signum (P xs) = P (map signum xs)
abs (P xs) = P (map abs xs)
fromInteger x = P [fromIntegral x]
polynomFromList = P
main :: IO()
main = do
let p1 = polynomFromList [1,0,0,0,0,0,1]
putStrLn $ " polynom1 = " ++ show p1 -- x^6+1
putStrLn $ " p1 + p1 = " ++ (show $ p1 + p1) -- 2x^6+2
putStrLn $ " p1 - p1 = " ++ (show $ p1 - p1) -- 0
putStrLn $ " p1 * p1 = " ++ (show $ p1 * p1) -- x^12+2x^6+1
let p2 = P [1,2,1]
putStrLn $ " polynom2 = " ++ (show p2) -- x^2+2x^1+1
putStrLn $ " p1 + p2 = " ++ (show $ p1 + p2) -- x^6+x^2+2x^1+2
putStrLn $ " p2 * x = " ++ (show $ p2 * (P [0,1])) -- x^3+2x^2+x^1
putStrLn $ " (p2 == p2 - (p2 - p1) + p2 - p1) is " ++ (show $ p2 == p2 - (p2 - p1) + p2 - p1) -- True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment