1

All these functions do the same thing:

def h0(f: Int => Int)(g: Int => Int)(x: Int) = f(g(x))
def h1(f: Int => Int, g: Int => Int)(x: Int) = f(g(x))
def h2(f: Int => Int)(g: Int => Int, x: Int) = f(g(x))
def h3(f: Int => Int, g: Int => Int, x: Int) = f(g(x))

Now I'm in polylemma: In which context should I "split" arguments ?

1 Answer 1

3

Split arguments are useful for type inference (as the compiler will go through them one at a time from left to right, so you can fix types on the left without getting into a muddle on the right--but the drawback then is that if you reference a generic type before you can fully infer it, you're stuck with partial progress by the time you hit the next parameter block), and for allowing braces instead of parentheses. So if you want syntax like

h0{ i =>
  math.round(math.pow(0.9123751,-i)).toInt
}{ j =>
  (10*math.sin(j)).toInt
}(2)

then you should split things up as in h0. Otherwise, you can do whatever makes sense for maximum clarity. In particular, h2 above is bad because it groups g and x for no apparent reason. Any of the others could be fine depending on context.

2
  • Could you clarify (or point to a more detailed explanation online) the drawback of being "stuck with partial progress by the time you hit the next parameter block"? And are there any other drawbacks?
    – max
    Apr 17, 2017 at 21:31
  • @max - You can play with things like foo[A, B](a: A, b: B)(b2: B) vs. foo[A, B](a: A)(b: B, b2: B) where the first B's type needs to be inferred but doesn't quite match the second (e.g. None and Some(1). In the former case, it will know something about B and just stop with whatever it's got and insist that b2 match what it's already decided (i.e. None.type). In the latter case, it doesn't know anything about B, so it does all the work at the second parameter block (e.g. figures out it should be Option[Int]). There aren't any other drawbacks I'm aware of.
    – Rex Kerr
    Apr 21, 2017 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.