F# Resources

You are here: main » core » operators


|

Meta

F# operators

Ref

val ref : 'a -> 'a ref

Create a mutable reference cell. Use the := operator to modify it, and the unary ! to access its value.

> let x = ref 12;;
val x : int ref = {contents = 12;}
 
> x := 4;;
val it : unit = ()
 
> 2 + !x;;
val it : int = 6

The main difference with the mutable keyword is the ability to escape its scope (mutable variables may not be captured by closures).

> let count =
  let counter = ref 0
  fun () -> incr counter; !counter;;
 
val count : (unit -> int)
 
> count();;
val it : int = 1
 
> count();;
val it : int = 2

See also

Pipelining and composition operators

// standard application
> string (sqrt 8.);;
val it : string = "2.82842712474619"
 
// pipelining: 8. goes into sqrt, the result is sent to string
> 8. |> sqrt |> string;;
val it : string = "2.82842712474619"
 
// sqrt and string are composed, the resulting function is then applied
> (sqrt >> string) 8.;;
val it : string = "2.82842712474619"
 
// reversed pipelining
> string <| sqrt 8.;;
val it : string = "2.82842712474619"
 
// it's often useful to use it with anonymous functions
> Array.init 5 <| fun x ->
    let y = x * x
    y + y / 2;;
val it : int array = [|0; 1; 6; 13; 24|]

See also