haskell - Creating Eq instances for polynomials -


representing polynomials in haskell:

newtype poly = p [a] x :: num => poly x = p [1]  instance (num a, eq a) => eq (poly a) 

e.g. p[1,2,3] = 3x^2 + 2x + 1

i want 2 polynomials equal if lists have equal (e.g. p[1,2,3] equal p[1,2,3]). equal if lists same except last elements 0's (e.g. p[1,2,3] equal p[1,2,3,0,0]).

however, don't know syntax how this.

implementing eq

just extend on jakes answer complete one:

i idea of removing leading zeros , end with:

newtype poly = p [a]  instance (num a, eq a) => eq (poly a)   p xs == p ys =     removeleadingzeros (reverse xs) == removeleadingzeros (reverse ys)  removeleadingzeros :: (eq a, num a) => [a] -> [a] removeleadingzeros (0 : xs) = removeleadingzeros xs removeleadingzeros xs = xs 

mind, don't have reverse again equality (as xs == ys <=> reverse xs == reverse ys)

here short test session in ghci:

λ> let p1 = p[1,2,3,0,0] λ> let p2 = p[1,2,3] λ> let p3 = p[1,2,3,0,4]  λ> p1 == p2 true  λ> p1 == p3 false  λ> p2 == p3 false 

using smart constructors

another possibility not publish p constructor , polynoms normalized form @ construction - has advantage can use deriving eq

module poly        ( poly, fromlist        )  newtype poly = p [a]                  deriving eq  fromlist :: (num a, eq a) => [a] -> poly fromlist = p . reverse . removeleadingzeros . reverse 

example

λ> let p1 = fromlist [1,2,3,0,0] λ> let p2 = fromlist [1,2,3]  λ> p1 == p2 true 

hiding all

as seem have implemented num (poly a) can remove fromlist exports - users have use arithmetic operators instead construct polynoms.

you have export x instead:

x :: (eq a, num a) => poly x = fromlist [0,1] 

remarks

depending on if p [] ok 0 polynom or if rather have p [0] in case instead might want rewrite removeleadingzeros to

removeleadingzeros :: (eq a, num a) => [a] -> [a] removeleadingzeros [0] = [0] removeleadingzeros (0 : xs) = removeleadingzeros xs removeleadingzeros xs = xs 

or it


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -