1

Since I began programming in Scala, I gravitated towards what seems to be a natural coding style in this language, which is easiest to explain with a simple example:

val a = {
def f1(p : Int) = ...
def f2(p : Int) =  ...
f1(12) * f2(100)
}

As you can see, the multiplication of the values, which, if you want to understand the code, is the first operation you should want to familiarize yourself with, is not to be found until the last line. Instead, you need to read through the pieces of the puzzle first (functions f1, f2) before you can see how they're actually arranged. For me, this makes the code harder to read. How are you dealing with this problem - or maybe you don't find it a problem at all?

Lukasz Gieron
  • 276
  • 2
  • 12

1 Answers1

1

One interesting approach might be to use the untyped macro proposal in macro-paradise to introduce a where binding, such that:

val a = (f1(12) * f2(100)) where {
  def f1(x : Int) = x + 1
  def f2(x : Int) = x + 2
}

gets rewritten to your code above. As I understand it, untyped macros would allow the non-existent identifiers f1 and f2 to exist past the pre-macro typecheck. I think the rewrite should be relatively simple, and then the second typecheck would catch any problems. However, I've never actually written any macros, so it's possible there's something about this which would fail!

If it were possible, I think it would be quite a nice form to have (and rewriting would solve problems with execution order) - if I get some time I may have a stab at writing it!

Edit: I've had a go at writing this, and bits of it turn out surprisingly easy. Code is available on github. Unfortunately, the best I can do so far is:

  val result = where ( f1(1) * f2(2), {
    def f1(x : Int) = x + 1
    def f2(x : Int) = x + 2
  })

The problem is that Scala's infix operators are just method calls, and so I'd need to have something constructed on the expression (f1(1) * f2(2)) in order to invoke them. But that's the very expression which won't type properly before macro resolution, so I'm not quite sure what to do. Time for a new question, methinks!

Impredicative
  • 5,039
  • 1
  • 17
  • 43
  • Thanks, this is interesting. Unfortunately it adds some clutter to the code, so I'll leave the question open in case someone else wants to chime in with his thoughts. – Lukasz Gieron Mar 15 '13 at 02:39
  • It's worth noting that the syntax is now a little better than that. The infix position isn't possible at present, though Eugene Burmako has suggested that it might be possible to add something. – Impredicative Mar 15 '13 at 09:22