Skip to content

Instantly share code, notes, and snippets.

@derekwyatt
Created February 16, 2012 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derekwyatt/1847337 to your computer and use it in GitHub Desktop.
Save derekwyatt/1847337 to your computer and use it in GitHub Desktop.
Attempt to simplify function composition from multiple partials using shapeless...
import shapeless._
import HList._
import Record._
object Shapeless {
type MyFunction = PartialFunction[Any, String]
object behaviourA extends Field[MyFunction] { override def toString = "BehaviourA" }
object behaviourB extends Field[MyFunction] { override def toString = "BehaviourB" }
object behaviourC extends Field[MyFunction] { override def toString = "BehaviourC" }
case object MessageA
case object MessageB
case object MessageC
def behaviourAType1: MyFunction = { case MessageA => "behaviourA type 1" }
def behaviourAType2: MyFunction = { case MessageA => "behaviourA type 2" }
def behaviourBType1: MyFunction = { case MessageB => "behaviourB type 1" }
def behaviourBType2: MyFunction = { case MessageB => "behaviourB type 2" }
def behaviourCType1: MyFunction = { case MessageC => "behaviourC type 1" }
def behaviourCType2: MyFunction = { case MessageC => "behaviourC type 2" }
var function = (behaviourA -> behaviourAType1) ::
(behaviourB -> behaviourBType1) ::
(behaviourC -> behaviourCType1) :: HNil
def func = function.get(behaviourA) orElse function.get(behaviourB) orElse function.get(behaviourC)
def runfunc() {
println("[MessageA]: " + func(MessageA))
println("[MessageB]: " + func(MessageB))
println("[MessageC]: " + func(MessageC))
}
def main(args: Array[String]) {
println("Run 1")
runfunc()
println("Run 2")
function = function + (behaviourA -> behaviourAType2)
runfunc()
println("Run 3")
function = function + (behaviourB -> behaviourBType2)
runfunc()
println("Run 4")
function = function + (behaviourC -> behaviourCType2)
runfunc()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment