Skip to content

Instantly share code, notes, and snippets.

@krishnanraman
Last active December 12, 2015 07:18
Show Gist options
  • Select an option

  • Save krishnanraman/4735596 to your computer and use it in GitHub Desktop.

Select an option

Save krishnanraman/4735596 to your computer and use it in GitHub Desktop.
ProportionMonoid
RESULT:
[tw-mbp13-kraman algebird (develop)]$ scala ProportionMonoid
List(1.0, 3.0)=>List(0.25, 0.75)
List(1.0, 2.0, 5.0, 2.0, 6.0, 4.0)=>List(0.05, 0.1, 0.25, 0.1, 0.3, 0.2)
SOURCE:
case class ProportionMonoid(x:Seq[Double]) {
private val n = x.size
if (n < 2) throw new RuntimeException("No proportions to compute!!!")
private var res = plus(Seq(x(0)),Seq(x(1)))
private var i = 2
while(i<n) {
res = plus(res,Seq(x(i)))
i += 1
}
val proportions = res.tail
def zero = Seq[Double]()
def plus(left : Seq[Double], right : Seq[Double]):Seq[Double] = {
val (a, prevsum) = (left(0),right(0))
(left.size,right.size) match {
case (1,1) =>
val sum = a+prevsum+0.0d
Seq(sum, a/sum, prevsum/sum)
case (_,1) => plus(right,left)
case (1,_) =>
val sum = a+prevsum
Seq(sum) ++ right.tail.map(x=>x*prevsum/sum) ++ Seq(a/sum)
case _ => // runtime error ?
Seq[Double]()
}
}
}
object ProportionMonoid extends App {
val a = Seq(1.0d,3.0d)
val b = Seq(1.0d,2.0d,5.0d,2.0d,6.0d,4.0d)
println( a + "=>" + ProportionMonoid(a).proportions)
println( b + "=>" + ProportionMonoid(b).proportions)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment