scala - What is Applicative Builder -


i scala , functional newbie , trying learn applicatives.

val o1 = some(1) val o2 = some(2) val o3 = some(3) val result = (o1 |@| o2 |@| o3) {_ + _ + _} 

there read applicatives , functors here

as per blog,

operator |@| product operation

and

combining applicatives product using |@| results in applicativebuilder takes function perform on product (since product + map common use case)

i finding difficult understand above 2 statements blog. example code in scala understand helpful.

i think key take away post, should reason applicative functors sentence:

hey, you got function wrapped bit of context, huh? not worry, know how apply kind of wrapped functions

applicative provides way of applying function wrapped in context on other wrapped values.

|@| , underlying type applicativebuilder scalazs way of constructing these applicatives via dsl.

from documentation (emphasis mine):

whereas scalaz.functor allows application of pure function value in context, applicative allows application of function in context value in context (ap)


operator |@| product operation

by "product operation" op means operation takes 2 values , wraps them inside applicativebuilder.

|@| method when invoked, returns instance of applicativebuilder:

final def |@|[b](fb: f[b]) = new applicativebuilder[f, a, b] {   val a: f[a] = self   val b: f[b] = fb } 

where f first order kind has apply instance defined:

implicit val f: apply[f] 

where apply applicative without point method.

combining applicatives product using |@| results in applicativebuilder takes function perform on product (since product + map common use case)

if take example , simplify bit 2 option[int]s:

import scalaz.scalaz._  val o1 = 1.some val o2 = 1.some val result: applicativebuilder[option, int, int] = o1 |@| o2 val finalres: option[int] = result.apply(_ + _) 

we:

  1. apply |@| 2 instances of option[int] , applicativebuilder[option, int, int]. option here our f, has instance of apply.
  2. after getting instance of builder, invoke it's apply method. provide function of shape int -> int , gives option[int], meaning still inside context, operation applied our values.

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -