Search code examples
scalacoding-stylesyntaxfunctional-programming

How can I write f(g(h(x))) in Scala with fewer parentheses?


Expressions like

ls map (_ + 1) sum

are lovely because they are left-to-right and not nested. But if the functions in question are defined outside the class, it is less pretty.

Following an example I tried

final class DoublePlus(val self: Double) {
    def hypot(x: Double) = sqrt(self*self + x*x)
}

implicit def doubleToDoublePlus(x: Double) =
    new DoublePlus(x)

which works fine as far as I can tell, other than

  1. A lot of typing for one method

  2. You need to know in advance that you want to use it this way

Is there a trick that will solve those two problems?


Solution

  • You can call andThen on a function object:

    (h andThen g andThen f)(x)
    

    You can't call it on methods directly though, so maybe your h needs to become (h _) to transform the method into a partially applied function. The compiler will translate subsequent method names to functions automatically because the andThen method accepts a Function parameter.

    You could also use the pipe operator |> to write something like this:

    x |> h |> g |> f