`
cookoo
  • 浏览: 646439 次
  • 性别: Icon_minigender_1
  • 来自: Shanghai
社区版块
存档分类
最新评论

Idiom of using in F#

    博客分类:
  • FP
阅读更多
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.

> 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.
      
分享到:
评论
2 楼 cookoo 2007-05-23  
呵呵,这是工作中用的,只是我有权选择罢了。
1 楼 simohayha 2007-05-22  
呵呵,羡慕楼主,可以有这么多的时间学习自己感兴趣的东西。

相关推荐

Global site tag (gtag.js) - Google Analytics