views:

95

answers:

1

I'm just getting started on F#, and when playing around with operator overloading, I've run into something I don't quite understand. Now, I understand that you can't use, for example, +* as an overloaded prefix operator; it can only be an infix operator. Here's where I get confused, however:

let (+*) a = a + a * a;;

If I run this, fsi tells me that the function (+*) is an int->int. Great, I can dig that -- it's not an overloaded operator, just a normal function named (+*). So, if I do:

printf "%d" ((+*) 6)

I'll get 42, as I expect to. However, if I try:

printf "%d" (+*) 6
or
printf "%d" (+*)6

It won't compile. I can't put the exact error up right now as I don't have access to an F# compiler at this moment, but why is this? What's going on with the binding here?

+6  A: 

It's interpreting this:

printf "%d" (+*) 6

Like this:

printf ("%d") (+*) (6)

In other words, passing three curried arguments to printf, the second of which is a reference to the function +*.

munificent
Ah, that makes some sense. However, the spacing syntax for parameters seems like it might make binding confusing. In what order to spaces bind parameters? I'm used to C-like languages with forced parentheses for parameters, so that kind of binding is obvious to me.
Perrako
Perrako, that is a great follow-up question. Post it as a separate question so we'll have a reference for the future (ie "How to get used to F# parameter passing syntax when I am used to C-like parameters?"). (I'm sorry that I can't answer myself; I learned Lisp before F# so I got used to the space syntax that way.)
Nathan Sanders
Never mind, I found this existing question which will probably answer yours: http://stackoverflow.com/questions/2725202/f-function-calling-syntax-confusion
Nathan Sanders
Thanks for the link! It does answer the question, but not super directly. With `printf "%d" (+*) 6`, it goes left to right, calling something like: `6|>printf "%d"`. That makes sense. What I'm not so sure about is the version with the space omitted; that is to say, `printf "%d" (+*)6` How/why can the compiler insert a space there, thus making them separate parameters?
Perrako
The ")" and "6" are separate lexical tokens in an expression, so it works the same way that "1+3*4" is equivalent to "1 + 3 * 4".BTW, you can use backwards pipe to control the precedence, so printf "%d" <| (+*) 6will work.
John Reynolds
Great answer! Thanks.
Perrako