functional programming - Pattern matching in anonymous function in Scala -


i'm beginner scala developer having problems coding exercise (5.12) taken book "functional programming in scala" paul chiusano.

i have function here, called unfold, takes initial state , function producing stream next states:

def unfold[a,s](z: s)(f: s => option[(a,s)]): stream[a] = f(z) match {   case some((h,t)) => h #:: unfold(t)(f)   case _ => stream.empty }  

for example, function 1 can create infinite stream of objects, e.g.

def constant[a](a: a): stream[a] = unfold(a)(_ => some(a,a))

now, want create fibonacci sequence, type:

def fibs: stream[int] = unfold((0,1))((a,b) => some(a,(b,a+b)))

i these errors:

  • missing parameter type b

  • expression of type some[((int,int),(nothing,string))] doesn't conform expected type option[(a_,(int,int))]

if use case keyword inside anonymous function passed unfold, like:

{ case (a,b) => some(a,(b,a+b))}

everything's fine.

so question is: what's difference between 2 implementations? type inference don't understand?

 { (a,b) => some(a, (b, a+b)) } 

is function takes two arguments - a , b, , returns option (of tuple). not need. want define function takes single (tuple) argument. 1 way this:

 { tuple => some(tuple._1, (tuple._2, tuple._1 + tuple._2)) } 

which expand this:

 { tuple =>       val = tuple._1      val b = tuple._2      // can shorter, automatic unapply here:      // val (a,b) = tuple      // pretty similar have `case`, right?      some(a, (b, a+b))  } 

this looks long, scala has special syntax construct lets deconstruct complex parameters anonymous functions "on fly", using syntax similar pattern matching (it calling unapply on input, same pattern match do):

 { case(a, b) => some(a, (b, a+b)) } 

this same above.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -