layout: post
title: “Comparing F# with C#: Downloading a web page”
description: “In which we see that F# excels at callbacks, and we are introduced to the ‘use’ keyword”
nav: why-use-fsharp
seriesId: “Why use F#?”
seriesOrder: 5

categories: [F# vs C#]

In this example, we will compare the F# and C# code for downloading a web page, with a callback to process the text stream.

We’ll start with a straightforward F# implementation.

  1. // "open" brings a .NET namespace into visibility
  2. open System.Net
  3. open System
  4. open System.IO
  5. // Fetch the contents of a web page
  6. let fetchUrl callback url =
  7. let req = WebRequest.Create(Uri(url))
  8. use resp = req.GetResponse()
  9. use stream = resp.GetResponseStream()
  10. use reader = new IO.StreamReader(stream)
  11. callback reader url

Let’s go through this code:

  • The use of “open” at the top allows us to write “WebRequest” rather than “System.Net.WebRequest”. It is similar to a “using System.Net“ header in C#.
  • Next, we define the fetchUrl function, which takes two arguments, a callback to process the stream, and the url to fetch.
  • We next wrap the url string in a Uri. F# has strict type-checking, so if instead we had written:
    let req = WebRequest.Create(url)
    the compiler would have complained that it didn’t know which version of WebRequest.Create to use.
  • When declaring the response, stream and reader values, the “use“ keyword is used instead of “let“. This can only be used in conjunction with classes that implement IDisposable.
    It tells the compiler to automatically dispose of the resource when it goes out of scope. This is equivalent to the C# “using“ keyword.
  • The last line calls the callback function with the StreamReader and url as parameters. Note that the type of the callback does not have to be specified anywhere.

Now here is the equivalent C# implementation.

  1. class WebPageDownloader
  2. {
  3. public TResult FetchUrl<TResult>(
  4. string url,
  5. Func<string, StreamReader, TResult> callback)
  6. {
  7. var req = WebRequest.Create(url);
  8. using (var resp = req.GetResponse())
  9. {
  10. using (var stream = resp.GetResponseStream())
  11. {
  12. using (var reader = new StreamReader(stream))
  13. {
  14. return callback(url, reader);
  15. }
  16. }
  17. }
  18. }
  19. }

As usual, the C# version has more ‘noise’.

  • There are ten lines just for curly braces, and there is the visual complexity of 5 levels of nesting*
  • All the parameter types have to be explicitly declared, and the generic TResult type has to be repeated three times.

* It’s true that in this particular example, when all the using statements are adjacent, the extra braces and indenting can be removed,
but in the more general case they are needed.

Testing the code

Back in F# land, we can now test the code interactively:

  1. let myCallback (reader:IO.StreamReader) url =
  2. let html = reader.ReadToEnd()
  3. let html1000 = html.Substring(0,1000)
  4. printfn "Downloaded %s. First 1000 is %s" url html1000
  5. html // return all the html
  6. //test
  7. let google = fetchUrl myCallback "http://google.com"

Finally, we have to resort to a type declaration for the reader parameter (reader:IO.StreamReader). This is required because the F# compiler cannot determine the type of the “reader” parameter automatically.

A very useful feature of F# is that you can “bake in” parameters in a function so that they don’t have to be passed in every time. This is why the url parameter was placed last rather than first, as in the C# version.
The callback can be setup once, while the url varies from call to call.

  1. // build a function with the callback "baked in"
  2. let fetchUrl2 = fetchUrl myCallback
  3. // test
  4. let google = fetchUrl2 "http://www.google.com"
  5. let bbc = fetchUrl2 "http://news.bbc.co.uk"
  6. // test with a list of sites
  7. let sites = ["http://www.bing.com";
  8. "http://www.google.com";
  9. "http://www.yahoo.com"]
  10. // process each site in the list
  11. sites |> List.map fetchUrl2

The last line (using List.map) shows how the new function can be easily used in conjunction with list processing functions to download a whole list at once.

Here is the equivalent C# test code:

  1. [Test]
  2. public void TestFetchUrlWithCallback()
  3. {
  4. Func<string, StreamReader, string> myCallback = (url, reader) =>
  5. {
  6. var html = reader.ReadToEnd();
  7. var html1000 = html.Substring(0, 1000);
  8. Console.WriteLine(
  9. "Downloaded {0}. First 1000 is {1}", url,
  10. html1000);
  11. return html;
  12. };
  13. var downloader = new WebPageDownloader();
  14. var google = downloader.FetchUrl("http://www.google.com",
  15. myCallback);
  16. // test with a list of sites
  17. var sites = new List<string> {
  18. "http://www.bing.com",
  19. "http://www.google.com",
  20. "http://www.yahoo.com"};
  21. // process each site in the list
  22. sites.ForEach(site => downloader.FetchUrl(site, myCallback));
  23. }

Again, the code is a bit noisier than the F# code, with many explicit type references. More importantly, the C# code doesn’t easily allow you to bake in some of the parameters in a function, so the callback must be explicitly referenced every time.