I apologize. I missed the end of your post where you asked for an example without using ref.

How about this solution that uses types?

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

type Counter() =
    let mutable x = -1
    
    member counter.Next() =
        x <- x + 1
        x


let next =
    let counter = Counter()
    (fun () ->
        counter.Next())

Here's the output from my FSI session:

1
2
3
4
5
6
7
8
> next;;
val it : (unit -> int) = <fun:next@70>
> next();;
val it : int = 0
> next();;
val it : int = 1
> next();;
val it : int = 2
By on 8/16/2008 8:18 PM ()

actually the reference cell version is not bad. what is the name/function/semantics of the := operator? F# could really use something like Scala's various pdf files (eg, Scala Refence, Scala by Example, ...)

thanks for the replies

By on 8/16/2008 9:06 PM ()

Glad to help! Reference cells are very simple. They boil down to these three operators:

1
2
3
4
5
6
7
val ref   : 'a -> 'a ref


val (:=) : 'a ref -> 'a -> unit


val (!)   : 'a ref -> 'a

I haven't seen the Scala pdf's but I agree that simple docs and how-tos are a great thing!

By on 8/17/2008 5:27 AM ()

With closures you need to use a reference cell like this:

1
2
3
4
5
let next =
    let x = ref (-1)
    (fun () ->
        x := !x + 1
        !x)

Here is the output from my FSI session:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> next;;


val it : (unit -> int) = <fun:next@47>


> next();;


val it : int = 0


> next();;


val it : int = 1


> next();;


val it : int = 2

By on 8/16/2008 8:08 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