Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. - Ввод полинома
  2.  
  3. inputPoly :: String -> Bool -> Int -> Int -> Int -> [(Int,Int)]
  4. inputPoly [] _ s c p = [(s*c,p)]
  5. inputPoly (x:xs) f s c p | f && (x == 'x') = inputPoly xs True s (if c == 0 then 1 else c) 1
  6. | x == '-' = (c * s, p) : (inputPoly xs True (-1) 0 0)
  7. | x == '+' = (c * s, p) : (inputPoly xs True 1 0 0)
  8. | f && (x == '^') = inputPoly xs False s c 0
  9. | f = inputPoly xs f s (c * 10 + (read [x] :: Int)) p
  10. | otherwise = inputPoly xs f s c (p * 10 + (read [x] :: Int))
  11.  
  12. -- Упрощение
  13.  
  14. redex :: [(Int, Int)] -> [(Int, Int)]
  15. redex x = filter ((/= 0) . fst) rlist
  16. where plist = sort $ nub $ map snd x
  17. rlist = map (\ n -> (sum (map fst (filter ((== n) . snd) x) ) , n) ) plist
  18.  
  19. -- Вывод полинома
  20.  
  21. showPoly :: [(Int, Int)] -> String
  22. showPoly [] = ""
  23. showPoly ((c, p):xs) | p == 0 = show(c) ++ showPoly xs
  24. | (c == 1) && (p == 1) = "+x" ++ showPoly xs
  25. | (c == -1) && (p == 1) = "-x" ++ showPoly xs
  26. | (c == 1) && (p /= 1) = "+x^" ++ show(p) ++ showPoly xs
  27. | (c == -1) && (p /= 1) = "-x^" ++ show(p) ++ showPoly xs
  28. | p /= 1 = (if c >0 then "+" else "") ++ show(c)++"x^" ++ show(p) ++ showPoly xs
  29. | otherwise = (if c >0 then "+" else "") ++ show(c)++"x" ++ showPoly xs
  30.  
  31. -- Производная
  32.  
  33. derivPoly :: [(Int, Int)] -> [(Int, Int)]
  34. derivPoly = redex . map (\ (c, p) -> (p * c, p-1))
  35.  
  36. -- Сложение полиномов
  37.  
  38. addPoly :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
  39. addPoly x y = redex $ x ++ y
  40.  
  41. -- Умножение полиномов
  42.  
  43. multPoly :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
  44. multPoly x y = redex $ foldl (\ acc c -> map (\ yy -> ( (fst yy) * (fst c), (snd yy)+ (snd c) ) ) y ++ acc) [] x
  45.  
  46. -- Умножение с вводом в естественном виде
  47.  
  48. multInput :: String -> String -> String
  49. multInput x y = showPoly $ multPoly (inputPoly x True 1 0 0) (inputPoly y True 1 0 0)
  50.  
  51. -- Сложение с вводом в естественном виде
  52.  
  53. addInput :: String -> String -> String
  54. addInput x y = showPoly $ addPoly (inputPoly x True 1 0 0) (inputPoly y True 1 0 0)
  55.  
  56. -- Дифференцирование с вводом в ест. виде
  57.  
  58. diffp :: String -> String
  59. diffp x = showPoly $ derivPoly $ inputPoly x True 1 0 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement