Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@oxbowlakes
Created March 13, 2012 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oxbowlakes/2028584 to your computer and use it in GitHub Desktop.
Save oxbowlakes/2028584 to your computer and use it in GitHub Desktop.
Position example (using monoid)
object Positions {
trait Investment
trait Position {
def investment: Investment
def tradingPnL: Option[Double]
def inventoryPnL: Option[Double]
final def totalPnL = inventoryPnL → tradingPnL
}
import Monoid._
import Monoid.Syntax._
class TraversableW[A](cc: Traversable[A]) {
def msum(implicit m: Monoid[A]): A = (m.identity /: cc)(m.mplus)
}
implicit def Traversable_Is_TraversableW[A](cc: Traversable[A]) = new TraversableW[A](cc)
case class Position0(investment: Investment, tradingPnL: Option[Double] = None, inventoryPnL: Option[Double] = None) extends Position
def main(args: Array[String]) {
object Vod extends Investment
object Msft extends Investment
object Ibm extends Investment
val posns = Position0(Vod, tradingPnL = Some(123)) :: Position0(Msft, inventoryPnL = Some(234)) :: Position0(Ibm, tradingPnL = Some(456), inventoryPnL = Some(567)) :: Nil
println( (posns map (_.totalPnL)).msum )
val petesBook = ((Position0(Vod, tradingPnL = Some(123)) :: Position0(Msft, inventoryPnL = Some(234)) :: Nil) map (p => p.investment -> p)).toMap
val davesBook = ((Position0(Ibm, tradingPnL = Some(567)) :: Position0(Msft, inventoryPnL = Some(234), tradingPnL = Some(876)) :: Nil) map (p => p.investment -> p)).toMap
println( petesBook mapValues (_.totalPnL) mplus (davesBook mapValues (_.totalPnL)) )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment