enhanced_null
enhanced_null

Reputation: 407

The case for point free style in Scala

This may seem really obvious to the FP cognoscenti here, but what is point free style in Scala good for? What would really sell me on the topic is an illustration that shows how point free style is significantly better in some dimension (e.g. performance, elegance, extensibility, maintainability) than code solving the same problem in non-point free style.

Upvotes: 25

Views: 3486

Answers (4)

Kevin Wright
Kevin Wright

Reputation: 49705

Quite simply, it's about being able to avoid specifying a name where none is needed, consider a trivial example:

List("a","b","c") foreach println

In this case, foreach is looking to accept String => Unit, a function that accepts a String and returns Unit (essentially, that there's no usable return and it works purely through side effect)

There's no need to bind a name here to each String instance that's passed to println. Arguably, it just makes the code more verbose to do so:

List("a","b","c") foreach {println(_)}

Or even

List("a","b","c") foreach {s => println(s)}

Personally, when I see code that isn't written in point-free style, I take it as an indicator that the bound name may be used twice, or that it has some significance in documenting the code. Likewise, I see point-free style as a sign that I can reason about the code more simply.

Upvotes: 25

Jim Hurne
Jim Hurne

Reputation: 7349

Scala's point-free syntax is part of the magic Scala operators-which-are-really-functions. Even the most basic operators are functions:

For example:

val x = 1
val y = x + 1

...is the same as...

val x = 1
val y = x.+(1)

...but of course, the point-free style reads more naturally (the plus appears to be an operator).

Upvotes: -5

Tom Crockett
Tom Crockett

Reputation: 31579

One appeal of point-free style in general is that without a bunch of "points" (values as opposed to functions) floating around, which must be repeated in several places to thread them through the computation, there are fewer opportunities to make a mistake, e.g. when typing a variable's name.

However, the advantages of point-free are quickly counterbalanced in Scala by its meagre ability to infer types, a fact which is exacerbated by point-free code because "points" serve as clues to the type inferencer. In Haskell, with its almost-complete type inferencing, this is usually not an issue.

Upvotes: 5

Landei
Landei

Reputation: 54574

I see no other advantage than "elegance": It's a little bit shorter, and may be more readable. It allows to reason about functions as entities, without going mentally a "level deeper" to function application, but of course you need getting used to it first.

I don't know any example where performance improves by using it (maybe it gets worse in cases where you end up with a function when a method would be sufficient).

Upvotes: 1

Related Questions