Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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.

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).

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top