天天看点

Idiom of using in F#

In Don Syme's [url=http://blogs.msdn.com/dsyme/archive/2006/12/18/DraftChaptersUpdateDec2006.aspx]excellent book drafts[/url] of his upcoming book [i]Expert F#[/i], the following code is used to demonstrate the quickness and easiness of F# interactive development.

[code]

> let req = WebRequest.Create("http://www.microsoft.com");;

val req : WebRequest

> let resp = req.GetResponse();;

val resp : WebResponse

> let stream = resp.GetResponseStream();;

val stream : Stream

> let reader = new StreamReader(stream) ;;

val reader : StreamReader

> let html = reader.ReadToEnd();;

val html : string = "<html>...</html>"

[/code]

However, writing codes in such way would be too imperative. By using the idiomatic [b]using[/b] function, we can write it in a more concise and safer form:

[code]#light

let http (url: string) =

let req = WebRequest.Create(url)

using (req.GetResponse())

(fun res -> using (res.GetResponseStream())

(fun stream -> let reader = new StreamReader(stream)

reader.ReadToEnd())) [/code]

The arguments of [b]using[/b] are:

[code]val it : 'a -> ('a -> 'b) -> 'b when 'a :> IDisposable = <fun:[email protected]>[/code]

Clearly, the first argument requires a resource that implements the IDisposable interface ( [b]:>[/b] is a special operator in F# for up-casting); then [b]using[/b] will feed the resource to a function to process further and finally will guarantee to release the resource when everything is done.