I'm writing simple polynomial-related library for my own needs. As for now, I'm working with just the polynomials in polynomial basis over GF(2), so they are represented simply as
case class Polynomial(coeffs: BitSet)
So I can just write something like
Polynomial(BitSet(0,1,2))
to represent
(x^2 + x + 1)
Now, I'm particularly proud about my multiplication function:
def *(that: Polynomial): Polynomial = Polynomial {
coeffs.foldLeft(BitSet.empty) { case (acc, i) => acc ^ that.coeffs.map(i +) }
}
But as for now, all my efforts to express reduction by some other polynomial modulo didn't show any similar result. I do indeed understand that division is somewhat more complex, but I currently have very, very dirty recursive solution and I don't like it at all. What I currently have is something like what follows (don't forget we are in GF(2)). (UPD: Simplified code to make it runnable outside class)
def foo(thisSet: BitSet, thatSet: BitSet): BitSet = {
var ts = thisSet
while (!ts.isEmpty && ts.max >= thatSet.max) {
ts = ts ^ thatSet.map(_ - thatSet.max + ts.max)
}
ts
}
It works fine (though I didn't write any test so far), but I'd like to have something neat (tail-recursive at most, but desirably just using folds/maps/reduces.