2007-02-21
Idiom of using in F#
关键字: f#
In Don Syme's excellent book drafts of his upcoming book Expert F#, the following code is used to demonstrate the quickness and easiness of F# interactive development.
However, writing codes in such way would be too imperative. By using the idiomatic using function, we can write it in a more concise and safer form:
The arguments of using are:
Clearly, the first argument requires a resource that implements the IDisposable interface ( :> is a special operator in F# for up-casting); then using will feed the resource to a function to process further and finally will guarantee to release the resource when everything is done.
> 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>"
However, writing codes in such way would be too imperative. By using the idiomatic using function, we can write it in a more concise and safer form:
#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()))
The arguments of using are:
val it : 'a -> ('a -> 'b) -> 'b when 'a :> IDisposable = <fun:clo@0>
Clearly, the first argument requires a resource that implements the IDisposable interface ( :> is a special operator in F# for up-casting); then using will feed the resource to a function to process further and finally will guarantee to release the resource when everything is done.
发表评论
- 浏览: 332522 次
- 性别:

- 来自: Montreal

- 详细资料
搜索本博客
我的相册
20059805856241
共 10 张
共 10 张
最新评论
-
Darcs简介
good 3x
-- by 夜鸣猪 -
Pratical Ocaml作者采访
现在主要用F#分析数据,因为比较舒服(人懒啊)。其实也只用到很少的FP特性,Ru ...
-- by cookoo -
Pratical Ocaml作者采访
一年多了,呵呵,cookoo能说说看,学习使用OCaml的进展和体会吗?
-- by billgui -
Memory - 柿岛伸次
还不错啊。
-- by hazzy -
Memory - 柿岛伸次
我很想下这个,可就是不能下。LZ能否提供链接
-- by yeshucheng






评论排行榜