36 people like it.

Create Disposable

This pattern is helpful when you want to do something temporarily and then restore some state. This was inspired by the System.Disposable.Disposable() class defined in System.Core.dll distributed by the Reactive Extensions for .NET (Rx) library.

Implementing IDisposable

1: 
2: 
3: 
4: 
5: 
6: 
open System
let createDisposable f =
    {
        new IDisposable with
            member x.Dispose() = f()
    }

Example: printing in the console with different colors

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
let changeColor color () = 
    let current = Console.ForegroundColor
    Console.ForegroundColor <- color
    createDisposable (fun () -> Console.ForegroundColor <- current)

let red = changeColor ConsoleColor.Red
let green = changeColor ConsoleColor.Green

using (red()) (fun _ ->  printfn "This is red : %A" [1 .. 3])
using (green()) (fun _ -> printfn "This is %A : %A" ConsoleColor.Green [1 .. 3])
namespace System
val createDisposable : f:(unit -> unit) -> IDisposable

Full name: Script.createDisposable
val f : (unit -> unit)
type IDisposable =
  member Dispose : unit -> unit

Full name: System.IDisposable
val x : IDisposable
IDisposable.Dispose() : unit
val changeColor : color:ConsoleColor -> unit -> IDisposable

Full name: Script.changeColor
val color : ConsoleColor
val current : ConsoleColor
type Console =
  static member BackgroundColor : ConsoleColor with get, set
  static member Beep : unit -> unit + 1 overload
  static member BufferHeight : int with get, set
  static member BufferWidth : int with get, set
  static member CapsLock : bool
  static member Clear : unit -> unit
  static member CursorLeft : int with get, set
  static member CursorSize : int with get, set
  static member CursorTop : int with get, set
  static member CursorVisible : bool with get, set
  ...

Full name: System.Console
property Console.ForegroundColor: ConsoleColor
val red : (unit -> IDisposable)

Full name: Script.red
type ConsoleColor =
  | Black = 0
  | DarkBlue = 1
  | DarkGreen = 2
  | DarkCyan = 3
  | DarkRed = 4
  | DarkMagenta = 5
  | DarkYellow = 6
  | Gray = 7
  | DarkGray = 8
  | Blue = 9
  ...

Full name: System.ConsoleColor
field ConsoleColor.Red = 12
val green : (unit -> IDisposable)

Full name: Script.green
field ConsoleColor.Green = 10
val using : resource:'T -> action:('T -> 'U) -> 'U (requires 'T :> IDisposable)

Full name: Microsoft.FSharp.Core.Operators.using
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view New version

More information

Link:http://fssnip.net/34
Posted:6 years ago
Author:Cesar Mendoza
Tags: idisposable , disposable , patterns