scala - How to improve the code of a method which uses 'Free monad'? -
i'm trying code inspects this slides free monad in scala, , made small project changed code.
the project here: https://github.com/freewind/free-the-monads
everything seems @ first, code clean , beautiful:
def insertandget() = { _ <- script.insert("name", "freewind") value <- script.get("name") } yield value def insertanddelete() = { _ <- script.insert("name", "freewind") _ <- script.delete("name") value <- script.get("name") } yield value def insertandupdateanddelete() = { _ <- script.insert("name", "freewind1") orivalue <- script.update("name", "freewind2") _ <- script.delete("name") finalvalue <- script.get("name") } yield (orivalue, finalvalue) but when logic complex, e.g. there script[option[_]], , need check option value decide something, can't use for-comprehension more, the code like:
private def islongname(name: string): script[boolean] = { size <- script.getlongnameconfig } yield size.exists(name.length > _) def upcaselongname(key: string): script[option[string]] = { script.get(key) flatmap { case some(n) => { islong <- islongname(n) } yield islong match { case true => some(n.touppercase) case false => some(n) } case _ => script.pure(none) } } i found free monad approach interesting , cool, i'm not familiar scalaz, , beginning learn monad things, not sure how improve it.
is there way make better?
ps: can clone project https://github.com/freewind/free-the-monads , try yourself
this use case optiont monad transformer:
import scalaz.optiont, scalaz.syntax.monad._ def upcaselongname(key: string): optiont[script, string] = { n <- optiont.optiont(script.get(key)) islong <- islongname(n).liftm[optiont] } yield if (islong) n.touppercase else n here optiont.optiont converts script[option[string]] optiont[script, string], , .liftm[optiont] raises script[boolean] same monad.
now instead of this:
println(upcaselongname("name1").runwith(interpreter)) you'd write this:
println(upcaselongname("name1").run.runwith(interpreter)) you have upcaselongname return script[option[string]] directly calling run there, if there's chance you'll need composing other option-y script-y things it's best have return optiont[script, string].
Comments
Post a Comment