You can't do this for a variety of reasons.

First, F# only allows a small number of prefix operators (and no postifx operators), see the spec

[link:research.microsoft.com]

for some info on that.

Second, to mutate a mutable variable, you'd have to pass it "byref" by prefixing the variable with an '&', so the call would look like "++ &x" anyway (if ++ were allowed as a prefix operator).

Finally, such side-effectful expressions are frowned upon anyway.

By on 11/23/2009 8:01 PM ()

Ok, thanks for the explanations. I guess that explains why I wasn't finding it... :)

So here is an example of the code I'm working on:

01 let GetWidgets connection =

02 let command = new SqlCommand("SELECT * FROM Widgets", connection)

03 use reader = command.ExecuteReader()

04 let index = ref 0

05 Console.Write("Loading widgets... ")

06 let top = Console.CursorTop

07 let left = Console.CursorLeft

08 seq { while reader.Read() do yield(reader) }

09 |> Seq.map (fun r ->

10 Console.SetCursorPosition(left, top)

11 index := !index + 1

12 if !index % 100 = 0 then Console.Write(!index)

13 {id = r.["Id"] :?> int; name = r.["Name"] :?> string})

14 |> Seq.toList

It's a utility to massage some data but I wanted some feedback during the process since it's going to be processing a lot of data. In a couple of long running spots I just want to display the current record number. Would the above approach be the best approach (Lines 4 & 11)? In C# I would have used the unary addition operator so that's why I was looking in that direction.

Thanks again,

m

By on 11/23/2009 8:36 PM ()

Note the incr and decr functions; you can use incr on line 11.

[link:msdn.microsoft.com]

[link:msdn.microsoft.com]

By on 11/23/2009 8:49 PM ()

Brian,

That's exactly what I'm looking for.

Thanks!

m

By on 11/24/2009 8:07 AM ()

Section 4.4, pages 29-30 of the current spec provide more details on this. Just define the operator:

1
2
3
4
5
6
7
8
9
10
 

> let (~++) x = x + 1;;

val ( ~++ ) : int -> int

> ++10;;

val it : int = 11

If you want to work on mutables, then you'll need to define the argument as a byref<int> (or ^a with inline I suppose) and take the address before calling it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 

> let (~++) (x : byref<int>) = x <- x + 1; x;;

val ( ~++ ) : byref<int> -> int

> let mutable x = 1;;

val mutable x : int = 1

> ++(&x);;

val it : int = 2

If you want it to return the value that was passed in before the mutation, then copy it inside the operator function first.

By on 11/23/2009 7:46 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper