Created
March 13, 2012 12:54
-
-
Save oxbowlakes/2028584 to your computer and use it in GitHub Desktop.
Position example (using monoid)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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