12

I currently use this function

let inc (i : int ref) =
    let res = !i
    i := res + 1
    res

to write things like

let str = input.[inc index]

How define increment operator ++, so that I could write

let str = input.[index++]
5
  • 2
    One question: why do you need this?
    – pad
    Apr 20, 2012 at 21:03
  • I'm with @pad on this one - while the question is valid, and an answer has been provided (as a prefix operator), the example given here is not F# style at all. Rarely a good reason to do something like this.
    – yamen
    Apr 20, 2012 at 21:12
  • I wanted that for readability. (I come from C++/C# background). I though it was possible but couldn't make it myself. Apr 20, 2012 at 21:21
  • You might also be interested in this.
    – Daniel
    Apr 20, 2012 at 22:04
  • 2
    @modosansreves "I wanted that for readability". You're doing it wrong. Describe the actual problem you are trying to solve using mutating increment in C++ if you want a useful answer.
    – J D
    Apr 22, 2012 at 10:27

2 Answers 2

13

You cannot define postfix operators in F# - see 4.4 Operators and Precedence. If you agree to making it prefix instead, then you can define, for example,

let (++) x = incr x; !x

and use it as below:

let y = ref 1
(++) y;;

val y : int ref = {contents = 2;}

UPDATE: as fpessoa pointed out ++ cannot be used as a genuine prefix operator, indeed (see here and there for the rules upon characters and character sequences comprising valid F# prefix operators).

Interestingly, the unary + can be overloaded for the purpose:

let (~+) x = incr x; !x

allowing

let y = ref 1
+y;;

val y : int ref = {contents = 2;}

Nevertheless, it makes sense to mention that the idea of iterating an array like below

let v = [| 1..5 |] 
let i = ref -1 
v |> Seq.iter (fun _ -> printfn "%d" v.[+i])

for the sake of "readability" looks at least strange in comparison with the idiomatic functional manner

[|1..5|] |> Seq.iter (printfn "%d")

which some initiated already had expressed in comments to the original question.

4

I was trying to write it as a prefix operator as suggested, but you can't define (++) as a proper prefix operator, i.e., run things like ++y without the () as you could for example for (!+):

let (!+) (i : int ref) = incr i; !i

let v = [| 1..5 |]
let i = ref -1
[1..5] |> Seq.iter (fun _ -> printfn "%d" v.[!+i])

Sorry, but I guess the answer is that actually you can't do even that.

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.