Skip to content

Instantly share code, notes, and snippets.

@imeredith
Last active December 16, 2015 04:09
Show Gist options
  • Save imeredith/5375530 to your computer and use it in GitHub Desktop.
Save imeredith/5375530 to your computer and use it in GitHub Desktop.
object comonadbuilder {
import scalaz._
import Scalaz._
case class Config(a: Option[String] = None, b: Option[Int] = None)
type Builder[A] = Config => A
def setFieldA(a: String) = (b:Builder[Config]) => b(Config(a=Some(a)))
//> setFieldA: (a: String)(comonadbuilder.Config => comonadbuilder.Config) => co
//| monadbuilder.Config
def setFieldB(a: Int) = (b:Builder[Config]) => b(Config(b=Some(a)))
//> setFieldB: (a: Int)(comonadbuilder.Config => comonadbuilder.Config) => comon
//| adbuilder.Config
val builder: Builder[Config] = c => c //> builder : comonadbuilder.Config => comonadbuilder.Config = <function1>
implicit val mo = new Monoid[Config] {
def zero: Config = Config()
// Members declared in scalaz.Semigroup
def append(f1: Config,f2: => Config): Config = Config(f1.a orElse f2.a, f1.b orElse f2.b)
} //> mo : scalaz.Monoid[comonadbuilder.Config] = comonadbuilder$$anonfun$main$1$
//| $anon$1@5b980c78
builder.cobind(setFieldA("aa")).cobind(setFieldB(3)).cobind(setFieldA("bb")).copoint
//> res0: comonadbuilder.Config = Config(Some(bb),Some(3))
}
object comonadbuilder {
import scalaz._
import Scalaz._
def withConfig = setter("config") //> withConfig: => (List[String] => comonadbuilder.Config) => comonadbuilder.Con
//| fig
def withStuff = setter("stuff") //> withStuff: => (List[String] => comonadbuilder.Config) => comonadbuilder.Conf
//| ig
type Builder[A] = List[String] => A
type Config = List[String]
def setter(opt: String) = (builder: Builder[Config]) => {
builder(opt :: Nil)
} //> setter: (opt: String)(List[String] => comonadbuilder.Config) => comonadbuild
//| er.Config
val builder: Builder[Config] = ls => Config(ls) //> builder : List[String] => comonadbuilder.Config = <function1>
builder.cobind(withConfig).cobind(withStuff).copoint
//> res0: comonadbuilder.Config = Config(List(stuff, config))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment