Safe Haskell | Safe-Inferred |
---|
First assignment for IB016, semester spring 2015 Name: Name Surname UID: 123456
- newtype Polynomial a = P {
- unP :: [a]
- polyPrint :: (Num a, Ord a, Show a) => String -> Polynomial a -> String
- eval :: Num a => Polynomial a -> a -> a
- belongs :: (Num a, Eq a) => (a, a) -> Polynomial a -> Bool
- yIntersect :: Num a => Polynomial a -> (a, a)
- quadratic :: Polynomial a -> Bool
- scalarTimes :: (Eq a, Num a) => a -> Polynomial a -> Polynomial a
- polyPlus :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
- polyMinus :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
- polyTimes :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
Polynomial type
newtype Polynomial a
The Polynomial type. Polynomials are represented as a list of coefficients
of increasing power. That is, the first element of list is constant element,
the second is the coefficient for x, the third coefficient for x^2 and so on.
There should be no trailing zeroes in the polynomial representation, i.e.
x^2 + 2x + 3 is represented as
not P
[3,2,1]
or similar.
P
[3,2,1,0,0]
Show a => Show (Polynomial a) |
Printing
polyPrint :: (Num a, Ord a, Show a) => String -> Polynomial a -> String
Print polynomial into pretty string representation.
The first argument is the variable name. Write spaces in between the term operators. Coefficients 1 and -1 should be diplayed only as a sign symbol. Do not display terms with zero coefficients.
>>>
polyPrint "x" (P [1, 2, 3, 4])
"4x^3 + 3x^2 + 2x + 1">>>
polyPrint "x" (P [-1, 0, -1, 3, -4])
"- 4x^4 + 3x^3 - x^2 - 1">>>
polyPrint "x" (P [0, 0, -1])
"- x^2">>>
polyPrint "x" (P [])
"0"
Evaluation
eval :: Num a => Polynomial a -> a -> a
Evaluate polynomial in given value. This can be viewed as converting the polynomial to the evaluation function.
>>>
eval (P [3, 1, -5]) 2
-15
belongs :: (Num a, Eq a) => (a, a) -> Polynomial a -> Bool
Determines, if a given point belongs to the polynomial.
>>>
belongs (2, -15) (P [3, 1, -5])
True
Properties
yIntersect :: Num a => Polynomial a -> (a, a)
Find the coordinates of the polynomial intersecting the y axis.
>>>
yIntersect (P [1, 2, -1])
(0,1)
quadratic :: Polynomial a -> Bool
Determines, if the polynomial is quadratic
>>>
quadratic (P [1, 2, -1])
True
Operations
scalarTimes :: (Eq a, Num a) => a -> Polynomial a -> Polynomial a
Multiply scalar and polynomial.
>>>
scalarTimes 3 (P [1, 2, 3])
P [3, 6, 9]>>>
scalarTimes 0 (P [1, 2, 3])
P []
polyPlus :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
Sum two polynomials.
>>>
polyPlus (P [1, 2, 3]) (P [2, 2, -3])
P [3, 4]
polyMinus :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
Make a difference of two polynomials.
>>>
polyMinus (P [2, -5, 3, 3]) (P [1, 2, 3])
P [1, -7, 0, 3]
polyTimes :: (Num a, Eq a) => Polynomial a -> Polynomial a -> Polynomial a
Multiply two polynomials.
>>>
polyTimes (P [2, 1]) (P [2, 3])
P [4, 8, 3]