scalaz - Is providing explicitly the context bound possible in Scala? -


in following code:

   def sum[a: monoid](xs: list[a]): = {      val m = implicitly[monoid[a]]      xs.foldleft(m.mzero)(m.mappend)    } 

if have in scope monoid[int] has mappend = _ + _, can call function explicit monoid[int] has different behavior? or solution use more verbose syntax second argument implicit monoid: monoid[int]?


the code exemple comes scalaz tutorial: http://eed3si9n.com/learning-scalaz/sum+function.html

at end author shows exemple of providing explicitly monoid, didn't use context bounds:

scala> val multimonoid: monoid[int] = new monoid[int] {          def mappend(a: int, b: int): int = * b          def mzero: int = 1        } multimonoid: monoid[int] = $anon$1@48655fb6  scala> sum(list(1, 2, 3, 4))(multimonoid) res14: int = 24 

context bounds nothing more syntactic sugar. following:

def sum[a: monoid](xs: list[a]) 

is extactly same as:

def sum[a](xs: list[a])(implicit evidence: monoid[a]) 

this means regardless of way defined sum method (either context bound or implicit parameter), can explicitly pass implicit parameter in sum(list(1, 2, 3, 4))(multimonoid)


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -