Understanding `andThen`
Asked Answered
O

1

31

I encountered andThen, but did not properly understand it.

To look at it further, I read the Function1.andThen docs

def andThen[A](g: (R) ⇒ A): (T1) ⇒ A

mm is a MultiMap instance.

scala> mm
res29: scala.collection.mutable.HashMap[Int,scala.collection.mutable.Set[String]] with scala.collection.mutable.MultiMap[Int,String] = 
                    Map(2 -> Set(b) , 1 -> Set(c, a))

scala> mm.keys.toList.sortWith(_ < _).map(mm.andThen(_.toList))
res26: List[List[String]] = List(List(c, a), List(b))

scala> mm.keys.toList.sortWith(_ < _).map(x => mm.apply(x).toList)
res27: List[List[String]] = List(List(c, a), List(b))

Note - code from DSLs in Action

Is andThen powerful? Based on this example, it looks like mm.andThen de-sugars to x => mm.apply(x). If there is a deeper meaning of andThen, then I haven’t understood it yet.

Octopus answered 29/11, 2013 at 19:43 Comment(0)
J
41

andThen is just function composition. Given a function f

val f: String => Int = s => s.length

andThen creates a new function which applies f followed by the argument function

val g: Int => Int = i => i * 2

val h = f.andThen(g)

h(x) is then g(f(x))

Johnnyjumpup answered 29/11, 2013 at 19:51 Comment(7)
wheres the benefit over writing : g(f(x)) ?Landre
@StefanKunze Maybe because it's easier to write val h = first andThen second andThen third andThen fourth than, for example, val h : String => Int = x => fourth(third(second(first(x)))) :) Fun fact: F# has >> operator for left-to-right function composition, so you can also save a few keystrokes.Trip
There is no advantage to writing f.andThen(g)(x) over g(f(x)). But there is an advantage to writing h(f andThen g) over having to write another function def fAndThenG(x:String) = f(g(x)) so that you can call h(fAndThenG). That is, if you want to pass the composed function as an argument, andThen allows you to do so quickly and anonymously.Engulf
why did you use val over def for functions f and g?Octopus
@StefanKunze It isn't syntactic sugar at all. It's a function. Syntactic sugar is syntax that is there to do something that other syntax could do. Functions are concrete implementations, not syntax. Scala has no syntax for function composition (just function application).Bamberg
The way that I like to reason about function composition is that it's like a Unix pipe. You're just evaluating a function of a function, f(g(x)), or f.g (x), which ties very closely to how Unix processes output text to streams, then taken as the input of another process, and so on and forth.Deepen
@StefanKunze the benefit is in more readability of code, since the order of function application replicates the way we speak in English.Oppugnant

© 2022 - 2024 — McMap. All rights reserved.