andThen in List scala -
has got example of how use andthen lists? notice andthen defined list documentations hasn't got example show how use it.
my understanding f andthen g means execute function f , execute function g. input of function g output of function f. correct?
question 1 - have written following code not see why should use andthen because can achieve same result map.
scala> val l = list(1,2,3,4,5) l: list[int] = list(1, 2, 3, 4, 5) //simple function increments value of element of list scala> def f(l:list[int]):list[int] = {l.map(x=>x-1)} f: (l: list[int])list[int] //function decrements value of elements of list scala> def g(l:list[int]):list[int] = {l.map(x=>x+1)} g: (l: list[int])list[int] scala> val p = f _ andthen g _ p: list[int] => list[int] = <function1> //printing original list scala> l res75: list[int] = list(1, 2, 3, 4, 5) //p works expected. scala> p(l) res74: list[int] = list(1, 2, 3, 4, 5) //but can achieve same 2 maps. point of andthen? scala> l.map(x=>x+1).map(x=>x-1) res76: list[int] = list(1, 2, 3, 4, 5)
could share practical examples andthen more useful methods filter, map etc. 1 use see above andthen, create new function,p, combination of other functions. use brings out usefulness of andthen, not list , andthen
andthen
inherited partialfunction
few parents inheritance tree list
. use list
partialfunction
when access elements index. is, can think of list
function index (from zero) element occupies index within list itself.
if have list:
val list = list(1, 2, 3, 4)
we can call list
function (because one):
scala> list(0) res5: int = 1
andthen
allows compose 1 partialfunction
another. example, perhaps want create list
can access elements index, , multiply element 2
.
val list2 = list.andthen(_ * 2) scala> list2(0) res7: int = 2 scala> list2(1) res8: int = 4
this same using map
on list, except computation lazy. of course, accomplish same thing view
, there might generic case you'd want treat list
partialfunction
, instead (i can't think of off top of head).
in code, aren't using andthen
on list
itself. rather, you're using functions you're passing map
, etc. there no difference in results between mapping list
twice on f
, g
, mapping once on f andthen g
. however, using composition preferred when mapping multiple times becomes expensive. in case of list
s, traversing multiple times can become tad computationally expensive when list large.
Comments
Post a Comment