Jul. 26th, 2009
categorical x^n in scala
Jul. 26th, 2009 01:58 pm
/**
* Builds a degree object (x^n) for a given object.
*
* @param x the source object
* @param n degree to which to raise object x
* @return x^n and its projections to x
* @TODO(vpatryshev): write good unitests
*/
def degree(x: O, n: Int): Option[(O, List[A])] = {
require(n >= 0, "Degree should be positive, we have " + n)
if (n == 0) {
terminal map(x => (x, List[A]()))
}
else {
degree(x, n - 1) flatMap (
value => {
val (x_n_1, previous_projections) = value
product(x, x_n_1) flatMap(
xn => {
val (p1, p_n_1) = xn
val projections = p1 :: previous_projections map (m(p_n_1, _))
Some((d0(p1), projections))
}
)
}
)
}
}
Seems like I am still learning to write code.