scala - Generic `implicit` operators for monads? -
scala - Generic `implicit` operators for monads? -
this part programming exercise , part practical.
i'd build operator | in illustration such that:
val x: option[int] = _ def fail: nil = _ val result = x | fail i have far , doesn't compile:
import language.implicitconversions import scala.util.{try, success, failure} trait orablefacilitator[t] { def apply[u](t: t, u: => u): u } implicit val optionorablefacilitator = new orablefacilitator[option[t]] { def apply[u, u >: t](t: option[t], u: => u): u = { t match { case some(v) => v case _ => u } } } implicit val tryorablefacilitator = new orablefacilitator[try[t]] { def apply[u, u >: t](t: try[t], u: => u): u = { t match { case success(v) => v case _ => u } } } implicit class orable[t](t: t) { def |[u](u: => u)(implicit orfacilitator: orablefacilitator[t, u]): u = { orfacilitator(t, u) } } what doing wrong?
i moved bunch of little things things work. tried comment places made changes running.
import language.implicitconversions import scala.util.{try, success, failure} // need wrap in object, since can't have vals @ top level object main extends app { // need capture in trait abstracting of // * → * kind, needs type takes type // input , returns type, such alternative or seek or list.. thing creating // orable going have in shape f[a], not f, // , there no reason prepare inner type trait orablefacilitator[f[_]] { // first parameter apply needs f[t], , homecoming type must supertype of t def apply[t, u >: t](t: f[t], u: => u): u } implicit val optionorablefacilitator = new orablefacilitator[option] { // here need take types input , output, adn must realted def apply[t, u >: t](t: option[t], u: => u): u = { t match { case some(v) => v case _ => u } } } implicit val tryorablefacilitator = new orablefacilitator[try] { def apply[t, u >: t](t: try[t], u: => u): u = { t match { case success(v) => v case _ => u } } } // can't wrap old t, has in shape // f[t] moved implcit create class // doesn't cuase have additional parameter list on our | // function ( prevent using inline ) implicit class orable[f[_], t](t: f[t])(implicit or: orablefacilitator[f]) { // vertical bar | keyword in scala, used formal "disjunction" operatior (|) instead. def |[u >: t](u: => u): u = { or(t, u) } } // , works: val noneint: option[int] = none val failint: try[int] = failure(new exception()) assert((some(0) : option[int]) .|(some(1)) == 0) assert((noneint | 2) == 2) assert(((success(0) : try[int]) | 3) == 0) assert((failint | 4) == 4) } scala operators implicit-conversion typeclass implicit
Comments
Post a Comment