F#-style pipe operator in Scala

This is super trivial, but sometime’s it’s nice to use the F# style pipe operator to write computations that read in the order they execute (basically postfix function application). In idiomatic Scala, this is usually accomplished by method calls and implicits to add extension methods. This is aided by the fact that many common functions for which postfix notation is convenient, like map, are pre-defined as methods on collections. But, general piping can still be a tool for the toolbox:

object MainModule {

  case class Pipeable[A](a: A) {
    def |>[B](f: A => B) = f(a)
  }

  implicit def convert[A](s: A) = Pipeable(s)  

  def main(args: Array[String]) {

    def map2[A, B](f: A => B)(xs: List[A]) = xs map f

    val test = List(1, 2, 3, 4, 5) |>
      map2 { _ + 1 } |>
      map2 { _ * 2 }

    println(test)

  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: