2 people like it.

Function returning counter function

A simple function that creates a counter function (with localized mutable state).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
/// When called with a single argument, returns a function 
/// that counts the number of times it has been called
let createCounter initial =
  let state = ref initial
  (fun () -> 
     let current = !state
     state := current + 1
     current)

// Create a counter and call it a few times
let counter = createCounter 0
let n0 = counter ()
let n1 = counter ()
let n2 = counter ()
val createCounter : initial:int -> (unit -> int)

Full name: Script.createCounter


 When called with a single argument, returns a function
 that counts the number of times it has been called
val initial : int
val state : int ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val current : int
val counter : (unit -> int)

Full name: Script.counter
val n0 : int

Full name: Script.n0
val n1 : int

Full name: Script.n1
val n2 : int

Full name: Script.n2
Raw view Test code New version

More information

Link:http://fssnip.net/lY
Posted:10 years ago
Author:Tomas Petricek
Tags: mutation , reference cell