TP

Upcoming F# events - learn Suave, FsLab & more!

Some people in the F# community have reputation for traveling too much. I do not know how that is possible, but as it happens, I will be visiting a couple of places in June and doing a number of talks, workshops and courses. So, if you are thinking about getting into F#, web development with F# using the amazing Suave library, playing with the new trendy F# to JavaScript compiler called Fable, or learning about the recent features in FsLab and Ionide, then continue reading!

The map includes all my travels, but not all of the pins are for F# events. I'm visiting Prague just to see my family (even though there is a new awesome F# meetup there) and my stop in Paris is attending Symposium for the History and Philosophy of Programming (although we might still do something with the local F# group too).

Published: Tuesday, 31 May 2016, 1:51 AM
Tags: c#, f#, functional programming, talks
Read the complete article

Comparing date range handling in C# and F#

I was recently working on some code for handling date ranges in Deedle. Although Deedle is written in F#, I also wrote some internal integration code in C#. After doing that, I realized that the code I wrote is actually reusable and should be a part of Deedle itself and so I went through the process of rewriting a simple function from (fairly functional) C# to F#. This is a small (and by no means representative!) example, but I think it nicely shows some of the reasons why I like F#, so I thought I'd share it.

One thing that we are adding to Deedle is a "BigDeedle" implementation of internal data structures. The idea is that you can load very big frames and series without actually loading all data into memory.

When you perform slicing on a large series and then merge some of the parts of the series (say, years 2010, 2012 and 2014), you end up with a series that combines a couple of chunks. If you then restrict the series (say, from June 2012 to June 2014), you need to restrict the ranges of the chunks:

Demonstration

As the diagram shows, this is just a matter of iterating over the chunks, keeping those in the range, dropping those outside of the range and restrictingthe boundaries of the other chunks. So, let's start with the C# version I wrote.

Published: Wednesday, 22 April 2015, 4:55 PM
Tags: f#, c#, deedle, linq, functional programming
Read the complete article

Pattern matching in action using C# 6

On year ago, on this very day, I wrote about the open-sourcing of C# 6.0. Thanks to a very special information leak, I learned about this about a week before Microsoft officially announced it. However, my information were slightly incorrect - rather then releasing the much improved version of the language, Microsoft continued working on language version internally called "Small C#", which is now available as "C# 6" in the Visual Studio 2015 preview.

It is my understanding that, with this release, Microsoft is secretly testing the reaction of the developer audience to some of the amazing features that F# developers loved and used for the last 7 years and that are coming to C# very soon. To avoid shock, these are however carefuly hidden!

In this blog post, I'm going to show you pattern matching which is probably the most useful hidden C# feature and its improvements in C# 6. For reasons that elude me, pattern matching in C# 6 is called exception filters and has some unfortunate restrictions. But we can still use it to write nice functional code!

Published: Wednesday, 1 April 2015, 11:41 AM
Tags: c#, fun, functional programming
Read the complete article

Upcoming F# book and event deals

Since I submitted my PhD thesis in December, I had a little bit of time to finish some of the things that I wanted to do for a really long time, but never quite found time to actually do them. This included getting the R provider to work on Mac and also creating a new web site for my various functional programming trainings and books. I even have a nice domain name:

The page also discusses a couple of business reasons for looking into functional programming. So, if you're a business person wondering why you should send your developers on an F# course, the site has the answers for you too! (Or if you are developer and need a page for your boss.) The other place to check out is the official F# Software Foundation web page is another great resource and the testimonials hosted there.

The page has some information about the various trainings we're offering at fsharpWorks and about the two F# books I co-authored (Real-World Functional Programming and brand new F# Deep Dives). I'm happy that we can offer some special deals on both the books and the F# FastTrack course in London, so if you're considering getting into F#, now is a good time!

Published: Friday, 27 March 2015, 11:16 AM
Tags: c#, f#, functional programming, talks
Read the complete article

Why you should learn F# in 2015 (and how)?

I guess that it might be a bit too late for adding to your list of new year's resulution now. But just if you still have an empty slot (or in case an originally taken slot has become available), your new year's resolution should be to get involved with F#!

Obviously, the goal of this blog post is to sell you some of my F# trainings and other materials - including the online course on F# in Finance and our FastTrack to F# course in London and New York and also the F# Deep Dives book. But to conceal this fact, I'm going to fill most of the blog post with useful information about F#, the F# Software Foundation and the F# community (but if you really just want to read about my courses, scroll down to the second section).

Published: Wednesday, 7 January 2015, 1:36 PM
Tags: c#, f#, functional programming, talks
Read the complete article

Welcome fsharpWorks & upcoming F# events

If you are following me or the #fsharp hashtag on Twitter, you might have already come across a link to fsharpWorks or one of the upcoming F# events organized by fsharpWorks. So, what is fsharpWorks and what are we planning for you?

Published: Tuesday, 20 May 2014, 1:47 PM
Tags: c#, f#, functional programming, talks
Read the complete article

BREAKING: Open-source C# 6.0 released

At last, the long wait is finally over! After 4 years of waiting, the fully managed implementation of the C# compiler codenamed "Roslyn" has been finally released. In the recent months, "Roslyn" has been slowly turning into vaporware, but thanks to the recent breakthrough, the team made an enormous progress over the last two months and even implemented a number of new C# 6.0 features.

The C# 6.0 compiler, together with the full source code has been released today!

UPDATE: In case you are reading this article later than on the day when it was published, let me just point out that this was released on 1 April 2014. Just to avoid any disappointments. Have fun ;-).

Published: Tuesday, 1 April 2014, 2:24 PM
Tags: c#, fun, functional programming
Read the complete article

How many tuple types are there in C#?

In a recent StackOverflow question the poster asked about the difference between tupled and curried form of a function in F#. In F#, you can use pattern matching to easily define a function that takes a tuple as an argument. For example, the poster's function was a simple calculation that multiplies the number of units sold n by the price p:

1: 
let salesTuple (price, count) = price * (float count)

The function takes a single argument of type Tuple<float, int> (or, using the nicer F# notation float * int) and immediately decomposes it into two variables, price and count. The other alternative is to write a function in the curried form:

1: 
let salesCurried price count = price * (float count)

Here, we get a function of type float -> int -> float. Usually, you can read this just as a function that takes float and int and returns float. However, you can also use partial function application and call the function with just a single argument - if the price of an apple is $1.20, we can write salesCurried 1.20 to get a new function that takes just int and gives us the price of specified number of apples. The poster's question was:

So when I want to implement a function that would have taken n > 1 arguments, should I for example always use a curried function in F# (...)? Or should I take the simple route and use regular function with an n-tuple and curry later on if necessary?

You can see my answer on StackOverflow. The point of this short introduction was that the question inspired me to think about how the world looks from the C# perspective...

val salesTuple : price:float * count:int -> float

Full name: Tuples-in-csharp.salesTuple
val price : float
val count : int
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
val salesCurried : price:float -> count:int -> float

Full name: Tuples-in-csharp.salesCurried

Published: Tuesday, 17 September 2013, 2:11 PM
Tags: c#, f#, functional programming
Read the complete article

Async in C# and F#: Asynchronous gotchas in C#

Back in February, I attended the annual MVP summit - an event organized by Microsoft for MVPs. I used that opportunity to also visit Boston and New York and do two F# talks and to record a Channel9 lecutre about type providers. Despite all the other activities (often involving pubs, other F# people and long sleeping in the mornings), I also managed to come to some talks!

One (non-NDA) talk was the Async Clinic talk about the new async and await keywords in C# 5.0. Lucian and Stephen talked about common problems that C# developers face when writing asynchronous programs. In this blog post, I'll look at some of the problems from the F# perspective. The talk was quite lively, and someone recorded the reaction of the F# part of the audience as follows...

Published: Monday, 15 April 2013, 4:00 AM
Tags: async, c#, f#
Read the complete article

The theory behind covariance and contravariance in C# 4

In C# 4.0, we can annotate generic type parameters with out and in annotations to specify whether they should behave covariantly or contravariantly. This is mainly useful when using already defined standard interfaces. Covariance means that you can use IEnumerable<string> in place where IEnumerable<object> is expected. Contravariance allows you to pass IComparable<object> as an argument of a method taking IComparable<string>.

So far, so good. If you already learned about covariance and contravariance in C# 4, then the above two examples are probably familiar. If you're new to the concepts, then the examples should make sense (after a bit of thinking, but I'll say more about them). However, there is still a number of questions. Is there some easy way to explain the two concepts? Why one option makes sense for some types and the other for different types? And why the hell is it called covariance and contravariance anyway?

In this blog post, I'll explain some of the mathematics that you can use to think about covariance and contravariance.

Published: Tuesday, 19 June 2012, 2:24 PM
Tags: c#, research
Read the complete article

F# Math (IV.) - Writing generic numeric code

Generic numeric code is some calculation that can be used for working with multiple different numeric types including types such as int, decimal and float or even our own numeric types (such as the type for clock arithmetic from the previous article of the series). Generic numeric code differs from ordinary generic F# code such as the 'a list type or List.map function, because numeric code uses numeric operators such as + or >= that are defined differently for each numeric type.

When writing simple generic code that has some type parameter 'T, we don’t know anything about the type parameter and there is no way to restrict it to a numeric type that provides all the operators that we may need to use in our code. This is a limitation of the .NET runtime and F# provides two ways for overcoming it.

Static member constraints are a unique feature of F# that is not available in other .NET languages, so if you're interested in writing numeric code for .NET, this may be a good reason for choosing F#. In C# or Visual Basic, you would be limited to the second option (which can be implemented in C#). In dynamic languages (like IronPython), everything is dynamic, so numeric computations can work with any numeric type, but will be significantly less efficient. In the rest of the article, we look at the three options summarized above.

This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see F# Math - Overview of F# PowerPack.

Published: Sunday, 27 November 2011, 5:19 PM
Tags: c#, functional, f#, math and numerics
Read the complete article

F# Math (I.) - Numeric types in PowerPack

In this article, we'll briefly look at two numeric types that are available in F# PowerPack. The type complex represents complex numbers consisting of real and imaginary parts. Both parts are stored as a floating point numbers. The type BigRational represents rational numbers consisting of numerator and denominator of arbitrary sizes. Integers of arbitrary size are represented using BigInteger type that is available in .NET 4.0 (in the System.Numerics.dll assembly). On .NET 2.0, the BigInteger type is also a part of F# PowerPack.

This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see F# Math - Overview of F# PowerPack.

Published: Wednesday, 2 November 2011, 2:34 AM
Tags: c#, functional, f#, math and numerics
Read the complete article

Real-World F# Articles on MSDN

More than a year ago, Mike Stephens from Manning (who was also behind my Real-World Functional Programming book) asked me if I'd be interested in collaborating on a project for MSDN. The idea was to collaborate with Microsoft on creating some additional content for the official F# Documentation.

A few days ago, the new content appeared on MSDN, so I finally have an excuse for the recent lack of blogging! Although the content contains a large number of new articles that are not based on my book, you can find it in the MSDN section named after my book, right under Visual F#. If you can't wait to check it out, here are all the links:

While working on the articles, I also wrote about a few topics that we didn't use in the final version. You'll see them on my blog in the next few days, as soon as I edit them into a blog post form. Continue reading for more information about individual chapters.

Published: Wednesday, 10 August 2011, 4:38 AM
Tags: functional, web, asynchronous, parallel, links, f#, c#
Read the complete article

Accessing loosely structured data from F# and C# (GOTO 2011)

About two weeks ago, I gave a talk at GOTO Conference in Copenhagen at a very interesting .NET session organized by Mark Seemann. In my talk, I focused on the impedance mismatch between the data structures that are used in programming languages (such as classes in C# or records and discriminated unions in F#) and the data structures that we need to access (such as database, XML files and REST services).

Clearly, both of the sides have some structure (otherwise, it wouldn't be possible to write any code against them!). Even an XML file that is returned by a REST service has some structure - although the only way to find out about the structure may be to call the service and then look at the result. In this article, I'll briefly summarize the ideas that I presented in the talk. Here are links to the slides as well as the source code from the talk:

Published: Thursday, 26 May 2011, 10:51 PM
Tags: c#, presentations, f#
Read the complete article

Beyond the Monad fashion (II.): Creating web forms with LINQ

The LINQ query syntax can be used for various things. Aside from writing queries, you can also use it to encode any monads. This has become a fashionable topic, so you can learn more about it at many .NET conferences (for example GOTO 2011). There are also many blog posts on this topic and I explained it in details in Chapter 12 of my book, which is available as a free sample chapter (PDF).

However, you can also use LINQ syntax for writing different types of computations. In a previous blog post, I introduced idioms (also called applicative functors) and I demonstrated how to use the join syntax in LINQ to write computations based on idioms. We looked at a slightly boring, but simple example - zipping of lists - and we also implemented matrix transposition.

In this blog post, we look at a more exciting example. I explain formlets, which is an idiom for building web forms. Formlets give us an elegant functional way to create reusable components that encapsulate both visual aspect (HTML) and behavior (processing of requests). You can think of them as functional ASP.NET controls. Formlets come from the Links project and they are now used in commercial products like WebSharper. In this article, you'll see that we can (mis)use LINQ to get a nicer syntax for writing code using formlets. My C# implementation of formlets is based on a nice F# formlets by Mauricio Scheffer.

Published: Monday, 14 March 2011, 5:14 PM
Tags: c#, research
Read the complete article

Beyond the Monad fashion (I.): Writing idioms in LINQ

Thanks to LINQ and Erik Meier, monads have become a fashionable topic in the C# developer community. Indeed, no serious developer conference on .NET can get away without having a talk on monads. The attractive thing about LINQ and monads is that the SelectMany operator roughly corresponds to the bind function that defines a monad. In practice, LINQ is used for working with collections of data (IEnumerable<T>), but you can also define bind (i.e. SelectMany) for some other data types and use the LINQ syntax for working with other types. You won't be really using the full LINQ syntax. You'll probably use just nested from clauses (for binding) and select at the end to return the result.

However, monads are not the only notion of computation that we can work with. More interestingly, they are also not the only notion of computation that you can encode using LINQ! In this article, I'll briefly introduce idioms (also called applicative functors), which is another useful abstract type of computations. Idioms can be used for a few things that cannot be done using monads.

A provocative summary of this article is: "Everyone who tells you that LINQ is a monad is wrong!"

The truth is that LINQ syntax can be used for encoding queries (obviously), monads (as you were told), but also for idioms as you'll learn today (and quite possibly for other types of computations). In this article, we look at a basic example, but I'll describe a more complex real-world scenario in the next blog post.

Published: Thursday, 10 March 2011, 1:26 PM
Tags: c#, research, functional
Read the complete article

Asynchronous C# and F# (III.): How does it work?

Some time ago, I started writing a series about the differences between the asynchronous model in F# (in Visual Studio 2010) and the asynchronous language extensions for C# proposed at PDC 2010. In the first article, I showed how both of the language features look and I highlighted a couple of differences. In the second article, I discussed the support for cancellation (available only in F#) and how the two models differ semantically (i.e. what are differences in the behaviour). However, I didn't talk about more techincal differences and, in particular, how is the asynchronous code compiled. We'll look at this topic today...

Although the C# asynchronous programming model is very similar to F# asynchronous workflows, the compilation looks quite different. The C# compiler uses a similar technique as when compiling iterators and creates a state machine, while the F# compiler uses an approach based on higher order functions (combinators) that's shared with (most) other computation expressions.

I won't discuss the syntax of F# asynchronous workflows or the C# asynchronous extensions in this article, so if you're new to one of these, here are links to other articles in this series:

Let's start by looking at the mechanism used in the C# compiler. If you already know how iterators work in C# 2.0, then you'll find it quite easy to understand. If you're not familiar with iterators, then don't worry - I'll make the explanation self-contained.

Published: Sunday, 21 November 2010, 3:15 AM
Tags: c#, functional, asynchronous, f#
Read the complete article

Asynchronous C# and F# (II.): How do they differ?

Anders Hejlsberg announced the support for asynchronous programming in the next version of C# announced at PDC 2010. The extension looks very similar to F# asynchronous workflows (which are already available in Visual Studio 2010). Despite the large similarity, there are a couple of differences between the two programming models. I already mentioned some of them briefly in the first article of this series. In this article, we'll look at some of the technical differences between the two models.

The most notable non-technical difference is that F# asynchronous workflows are already available in a supported version of Visual Studio and can be used on a large number of .NET runtimes (including, for example, Windows Phone and Silverlight). However, there are surprisingly many technical differences as well. In this article, I'll talk about the support for cancellation, which is available in F# and is not (currently) available in the C# preview. We'll also look at the difference between model where tasks are created as running and the delayed model.

This article is the second part of a short series about the asynchronous programming support in C# and F#. The previous article shows a simple example in both of the languages and the next articles explain how does the feature work (and how you can customize its behavior) as well as how to call F# libraries from C#:

Let's start by looking at, perhaps, the most important technical difference - the built-in support for cancellation available in F# asynchronous workflows.

Published: Monday, 1 November 2010, 4:36 PM
Tags: c#, asynchronous, f#
Read the complete article

Asynchronous C# and F# (I.): Simultaneous introduction

One of the exciting new technologies that was announced at PDC 2010 is the support for asynchronous programming in C#. So what exactly is asynchronous programming? Many applications today need to connect to some service or external data source including, for example, Web Services and REST APIs. These calls may take a long time to run, but we want to run them without blocking the application.

Currently, you can run the operation on a background thread or using a Task, but coordinating multiple such operations is difficult. What if you for example need to wait until any (or all) of downloads complete and run some more code then? This is not only difficult, but it also scales badly, because blocking .NET threads is a bad practice (Threads are expensive and when they're just waiting for other operation to complete, we're wasting valuable resources). This problem has been the main motivation for including asynchronous workflows in F# about 3 years ago. In F#, this also enabled various interesting programming styles - for example creating GUI using asynchronous workflows (also discussed in Chapter 16 of my book and in in my recent talk). The C# asynchronous programming support and the await keyword is largely inspired by F# asynchronous workflows (I was quite surprised that F# wasn't more visibly mentioned in the PDC talk).

In this article series, I'll demonstrate both F# and C# asynchronous programming model, I'll look at features that are missing in one or the other as well as a few subtle differences (that may be unexpected) and finally, I'll write about writing (asynchronous) F# libraries that are easy to use from C#. The plan for the series is following:

Let's start with a brief overview of asynchronous programming features in C# and F#...

Published: Friday, 29 October 2010, 4:34 AM
Tags: c#, asynchronous, f#
Read the complete article

Using custom grouping operators in LINQ

You can use LINQ to write queries that perform grouping of data using group by or ordering of data using orderby clause. LINQ provides the default (and the most common) implementation of both of the operations, but sometimes you may need a slightly different behavior when grouping or ordering data (this article is motivated by a question on StackOverflow which needs to do exactly that for grouping).

Let's look at a simple example, which shows when we may need a different behavior when grouping data. For example, we may have the following list of stock trades containing a name of a stock and the price of the trade (stored for example as a list of TradeInfo classes with properties Name and Price):

{ { Name = "MSFT", Price = 80.00 },
  { Name = "MSFT", Price = 70.00 },
  { Name = "GOOG", Price = 100.00 },
  { Name = "GOOG", Price = 200.00 },
  { Name = "GOOG", Price = 300.00 },
  { Name = "MSFT", Price = 30.00 },
  { Name = "MSFT", Price = 20.00 } }

Now, we may want to group adjacent trades into a single summary record which will contain the name of the stock (which is same for all trades in each group), the number of trades in the group and an average price in the group. The desired results are:

{ { Name = "MSFT", Count = 2, AvgPrice = 75.00 },
  { Name = "GOOG", Count = 3, AvgPrice = 200.00 },
  { Name = "MSFT", Count = 2, AvgPrice = 25.00 } }

The operation that we want to do is very similar to group by in LINQ, but it doesn't do quite the same thing! If we used group by, we would get only two groups as the result. However, as I wrote earlier, we want to group only adjacent trades. You could write your own extension method to do this, but then you need to leave the elegant LINQ query syntax. In this article, I'll show you how to get the desired results using a simple LINQ query with a group by clause...

Published: Sunday, 7 February 2010, 8:13 PM
Tags: academic, c#, parallel
Read the complete article

Source code for Real World Functional Programming available!

As you can see, there has been quite a bit of silence on this blog for a while. There are two reasons for that - the first is that I'm still working on the book Real World Functional Programming, so all my writing activities are fully dedicated to the book. The second reason is that I'm having a great time doing an internship in the Programming Principles and Tools group at Microsoft Research in Cambridge with the F# team and namely the F# language designer Don Syme. The photo on the left side is the entrance gate to the Trinity College of the Cambridge University taken during the few days when there was a snow. I recently started using Live Gallery, so you can find more photos from Cambridge in my online gallery. Anyway, I just wanted to post a quick update with some information (and downloads!) related to the book...

Published: Thursday, 12 February 2009, 2:10 AM
Tags: random thoughts, c#, functional, universe, asynchronous
Read the complete article

Functional Programming in .NET using C# and F# (Manning Greenpaper)

Functional programming languages have been around for a while and were always astonishing for their ability to express the ideas in a succinct, declarative way allowing the developer to focus on the essence of problem rather than on technical details of the solution. Recently, functional paradigm is gaining new prominence as an efficient way to handle development of multi-processor, parallel and asynchronous applications.

Functional ideas are arising in C# as well as in other main-stream languages and functional languages are becoming an alternative for real-world projects. Also, Microsoft recently introduced a new language called F#, which has a strong background in traditional functional languages, but as a .NET language also benefits from the rich .NET and Visual Studio ecosystem.

Book cover
Available via MEAP | 500 pages
Softbound print: March 2009 (est.)

This article is partially an excerpt from my book Real-world Functional Programming in .NET [1]. Thanks to my editors at Manning I have the permission to publish it on my blog. We’ll look at several aspects of functional programming and how the same concepts, which are essential for the functional paradigm, look in the F# and in C# 3.0 with LINQ. We will shortly look at the basic programming language features like lambda functions and type inference that are now available in both F# and C#. Functional programming isn’t only about language features, but also about using different programming style, so we’ll look at some high level concepts as well. These include using immutable data structures for developing code that can be executed in parallel and writing code in a more declarative style.

Thanks to the combination of C# 3.0 and F#, this article shows the ideas in a way that should be familiar to you in C#, but also shows a further step that you can take with a primarilly functional language F#. If you're a .NET developer and you want to understand what functional programming is and how it can help you to become better and more productive then continue reading. If you'll find this article interesting, then don't forget to check out the book, which explains everything in larger detail and discusses many other interesting ideas.

Published: Thursday, 11 December 2008, 1:48 AM
Tags: functional, c#, parallel, meta-programming, writing, f#
Read the complete article

Reactive Programming (IV.) - Developing a game in Reactive LINQ

In this part of the article series about Reactive LINQwe're going to implement a slightly more complicated application using the library that I introduced in the previous three articles. We're going to use basic event stream queries from the second article as well as advanced operators introduced in the third part. This time, I'll also show the F# version of all the examples, so we're going to build on the ideas from the first part.

I originally wanted to write the demo only in Visual Basic, because I think that it is really amazig to show an idea that came from functional programming in a language that no one (maybe until recently) connects with functional programming. Then I realized that I really want to show the F# version too, because F# was an inspiration for the whole Reactive LINQ idea and it is interesting alone as well. But finally, I thought that don't showing the C# version may look offensive to many readers (especially since I'm still C# MVP...). So, I ended up writing the game in all three languages, but the code is surprisingly similar in all of them!

Published: Monday, 24 November 2008, 3:00 AM
Tags: c#, functional
Read the complete article

Reactive Programming (III.) - Useful Reactive LINQ Operators

In the previous article, I introduced Reactive LINQ. I explained the different point of view that we can use when working with .NET events. The idea is that .NET events can be viewed as streams of values. The value is information about the event (such as position of a mouse click or a mouse movement). These streams can be processed using LINQ queries - we can for example filter all values that are not interesting for us using where LINQ clause. For example if we want to handle clicks only in some specified area.

In the previous article, I talked about basic LINQ query operators such as select and where and some useful methods that Reactive LINQ provides (for example for merging event streams). Today, we'll take a look at two more advanced kinds of operations that we can use for working with event streams. In particular, we'll talk about aggregation operators (that you certainly know from LINQ) and about switching. Switching is a concept from functional reactive programming and it allows us to change dynamically how the application behaves. However, I'll explain this in a more detail soon.

In this article, I'm going to use mostly C# (and some Visual Basic). The functionality that I'm describing in this part isn't part of the standard F# Event module that I discussed in the first part. I implemented most of them in F# too, but I'm not going to write the samples in both of the versions in this part. If you've seen the first two articles, you'll be definitely able to use the F# versions as well, because they follow exactly the same ideas as the C#/LINQ versions. I'm going to talk about a larger demo application in the last section and I'll show an F# version as well, so you'll see some F# examples in the next part. This part serves more as a reference of the available operators, so you may read only some parts of it, then jump to the last one (to see an exciting example!) and then come back here.

Published: Friday, 21 November 2008, 7:59 PM
Tags: functional, c#
Read the complete article

Reactive programming (II.) - Introducing Reactive LINQ

In this article I'm going to introduce my project Reactive LINQ. This is largely inspired by the ideas that come from functional reactive programming in the Haskell language and from functionality that's available for working in events in F#. I introduced these ideas in my previous article in this mini-series, so if you're interested in learning more about these interesting technologies, you should definitely read the previous article about First class events in F#.

In this article, we're going to look how to apply the same ideas to the C# language and how to use LINQ queries for processing events. This article is just another my article that shows how to implement some idea from functional programmin in C#. I believe this will once again show that the new features in the C# 3.0 aren't just about querying databases, but are more widely useful even in situations that are not directly related to data-processing.

Published: Wednesday, 19 November 2008, 7:57 PM
Tags: functional, c#
Read the complete article

Reactive programming (I.) - First class events in F#

I believe that the LINQ project and changes in C# 3.0 and VB 9 are interesting because they allow rewriting of many ideas from functional programming. An ability to express queries easily is one of these ideas, but it is definitely not the only one. There are many other interesting ideas. The C# 3.0 language isn't primary a functional language, so it isn't easy to discover the idea if you use only C#, but it is possible to implement it if you know the idea already.

I already wrote a few interesting C# examples that were inspired by some functional idea. I'm a big fan of the F# language, so it is not a surprise that I started with an F# version of the problem and then looked at the way to do the same thing in C#. In particular, this is how my article about building dynamic queries in C# came to the existence - the F# version used FLINQ and Quotations and then I demonstrated how to do the same in C# using expression trees. Another example is my article about asynchronous programming in C# using iterators, which shows how to implement something like F# asynchronous workflows using iterators in C# 2.0.

Functional Reactive Programming

Today, I'm going to look at another very interesting idea from functional programming. It is called Functional Reactive Programming and it comes from the Haskell community. You can find a list of related Haskell projects here. However, similar things (though they are not purely functional and simplified) are available in the F# language as well. Don Syme introduced them in his blog post called F# First Class Events: Simplicity and Compositionality in Imperative Reactive Programming. In this article, I'm going to briefly introduce the implementation available in F# and I'll extend it a little bit to allow some more interesting things. In the second article from this series, I'll show how to implement the same thing in C# 3.0 (and in VB 9 too!)

Published: Sunday, 16 November 2008, 5:14 PM
Tags: functional, c#, asynchronous, meta-programming, f#
Read the complete article

Calculating with infinite sequences on MSDN

About a year ago, I wrote an article about using lazy computations in C# 3.0. It was published by the C# Community PM Charlie Calvert at the C# Developer Center. The article was a first of two articles where I wanted to demonstrate that C# 3.0 can be used for implementing useful constructs known from functional languages. I realized that I never posted the link to the second article to my blog, so you can find the annotation and link below.

However, I remembered about these two articles because I was just working on chapters 11 and 12 of the Real-world Functional Programming in .NET book that I’m writing. Lazy values, which were the topic of my first article, are discussed in the second part of chapter 11 and IEnumerable and F# sequences are the topic for the first part of chapter 12. Because I already wrote two articles on this topic, I had to think really hard to find better (and still simple enough) examples where these concepts are useful in practice. I also finally have enough space to show how these two concepts relate and talk about some interesting background – for example in Haskell, lazy sequences are in fact just ordinary lists that are lazy thanks to the Haskell nature.

A year ago, I definitely wouldn’t believe that today, I’ll be writing about the same topics, but this time as part of a book that has partly the same goal as these two articles – to show that functional programming ideas are really useful in the real-world and can enrich your programming toolbox (no matter whether you’re using C# or F# language). Anyway, here is the link to the second article – as usual when I look at something that I worked on a long time ago, I think I should rewrite it to make it better :-), but it still gives you an idea what is the book that I’m working on about...

Published: Thursday, 13 November 2008, 2:36 AM
Tags: c#, functional, universe, writing, links
Read the complete article

Functional Programming in .NET book - An update

Recently, I announced on my blog that I’m working on a book for Manning called Real world Functional Programming in .NET. The goal of the book is to explain the most interesting and useful ideas of functional programming to a real world C# developer. I'm writing this book, because I believe that functional programming is becoming increasingly important. Here is a couple of reasons why you should have this book on your bookshelf:

The book is available via the MEAP (Manning Early Access Program) and if you want to get a better idea what is the book about, you can read the first chapter for free. Anyway, it is more than a month since I posted the announcement, so I decided to write a brief update....

Published: Monday, 20 October 2008, 10:10 PM
Tags: functional, c#, universe, web, writing
Read the complete article

Asynchronous Programming in C# using Iterators

In this article we will look how to write programs that perform asynchronous operations without the typical inversion of control. To briefly introduce what I mean by 'asynchronous' and 'inversion of control' - asynchronous refers to programs that perform some long running operations that don't necessary block a calling thread, for example accessing the network, calling web services or performing any other I/O operation in general. The inversion of control refers to the code structure that you have to use when writing a code that explicitly passes a C# delegate as a callback to the asynchronous method (typically called BeginSomething in .NET). The asynchronous method calls the delegate when the operation completes, which reverses the way you write the code - instead of encoding the control flow using typical language constructs (e.g. while loop) you have to use global variables and write your own control mechanism.

The funny thing about this article is that it could have been written at least 3 years ago when a beta version of Visual Studio 2005 and C# 2.0 became first available, but it is using iterators in a slightly bizarre way, so it is not easy to realize that this is possible. Actually, I will use some C# 3.0 methods in the article as well, but only extension methods and mainly just to keep the code nicer. As with my earlier article about building LINQ queries at runtime, I realized that it can be done in C# when I was playing with the F# solution (called F# Asynchronous Workflows), where this approach is very natural, so I will shortly mention the F# implementation as well.

Published: Thursday, 15 November 2007, 3:08 AM
Tags: c#, parallel, asynchronous
Read the complete article

Lazy Computation in C# on MSDN

I think that one of the interesting things about C# 3.0 is that it gives you the ability to use many techniques known from functional languages (like Haskell or F#). Most of the articles about C# 3.0 and LINQ focus on the queries and LINQ to SQL, but I believe that using these functional techniques deserve some attention as well. This is why I'm very happy that my article about one of these techniques - representing lazy computations - is now available at the C# Developer Center. I would like to thank to Charlie Calvert [^], who is the Community Program Manager for C# and who edited and published my article there. Here is the annotation:

Most of the programming languages used in practice (including for example C#, VB.NET, C++, Python or Java) employ so called eager evaluation, which means that the program evaluates all expression and statements in the order in which they are written, so all the preceding statements and expressions are evaluated before executing the next piece of code. This, for example, means that all arguments to a method call are evaluated before calling the method. Sometimes it may be useful to delay an execution of some code until the result is actually needed, either because the result may not be needed at all (but we can’t tell that before executing some computation) or because we don’t want to block the program for a long time by executing all computations in advance and instead we want to execute the computations later, when we will actually need the result.

In this article we will look how these lazy computations can be written in C# (using some of the new language features from version 3.0). We will first implement a Lazy class to represent this kind of computation, then look at a few simple examples to demonstrate how the class can be used, and finally we will examine one slightly more complicated, but practically useful application.

You can read the complete article here: Lazy Computation in C# [^]

Published: Saturday, 6 October 2007, 1:29 AM
Tags: c#, universe, functional, links
Read the complete article

Building LINQ Queries at Runtime in F#

In an article about building LINQ queries at runtime in C# 3.0, I described how you can build a LINQ query dynamically, for example by combining a set of conditions using the 'or' operator in the where clause. I mentioned that the way I implemented it is largely influenced by the F# language, which provides very natural way for manipulations with code like this. In this article I will first shortly introduce FLINQ sample, which is an F# library implementing LINQ support and than I will implement the same examples I presented in the earlier article in F#.

Published: Saturday, 18 August 2007, 2:38 AM
Tags: c#, meta-programming, f#
Read the complete article

Building LINQ Queries at Runtime in C#

Since the first beta versions of LINQ we could hear comments that it is perfect for queries known at compile-time, however it is not possible to use it for building queries dynamically at runtime. In this article I show that this can be actually done very well for most of the common cases. The solution offered by Microsoft (mentioned in [1]) is to build query from a string, however this has many limitations and it in fact goes completely against what LINQ tries to achieve, which is writing queries in a type-safe way with full compile-time checking. In this article I will first show a few support functions to make the life a bit easier and then we will use them for building two sample applications that allows user to build a query dynamically. The solution is largely motivated by my previous use of F#, where working with “expressions” is possible at more advanced level, however I’ll write about F# later and now let’s get back to C# 3.0...

Published: Monday, 30 July 2007, 2:10 AM
Tags: c#
Read the complete article

CLinq - LINQ support for the C++/CLI language

I started working on this project, because I attended C++ class at our university and I had to do some application in C++. Because I hate doing useless projects I wanted to work on something interesting and so I started thinking whether it would be possible to enable LINQ support in C++/CLI...

C++/CLI is a very flexible language and the following example proves that enabling LINQ support in C++/CLI isn't impossible. The following database query returns name of contact and company for all customers living in London:

// create connection to database
NorthwindData db(".. connection string ..");

// declare database query
Expr<Customers^> cvar = Var<Customers^>("c");
CQuery<String^>^ q = db.QCustomers
  ->Where(clq::fun(cvar, cvar.City == "London"))
  ->Select(clq::fun(cvar, 
      cvar.ContactName + Expr<String^>(", ") + cvar.CompanyName));

// execute query and output results
for each(String^ s in q->Query)
  Console::WriteLine(s);

If you are interested in more information about CLinq project you can...

Published: Friday, 2 March 2007, 5:11 PM
Tags: .net, academic, c#
Read the complete article

Can't return anonymous type from method? Really?

One of the new features introduced in C# 3.0 which will be available in Visual Studio "Orcas" (currently in CTP version) is anonymous type. Anonymous type is something very similar to tuple type from Cω [1] (which is based on tuple types known from many functional programming languages including F#). Anonymous types are extremely useful in LINQ queries, because it allows you to construct type with several properties without declaring the type (with all the properties). Example of query with anonymous type looks like this:

var q = from c in db.Customers
        where c.Country = "Czech Republic"
        select new { FullName=c.Name+" "+c.Surname, Address=c.Address };

Ok, it's probabbly not the best example, but it demonstrates the point - you want to return some information from query and you don't need to declare type that contains FullName and Address properties before, because you need it only for this single query (and you want to return only these two fields, so you don't transfer additional data that you don't need from database).

Now let's get to the second point...

Published: Tuesday, 23 January 2007, 11:54 PM
Tags: c#
Read the complete article

Concepts behind the C# 3.0 language

One of the lectures that I attended last year was Programming Methodology and Philosophy of Programming Languages. The lecture was mostly about history of programming languages and how several features evolved, disappeared and than after many years appeared again in another programming language.

As I final work I decided to write an article that describes ideas that influenced the design of the C# 3.0 language. Some of these features are known from functional languages (for example from LISP or Haskell), some other were developed at Microsoft Research and appeared in the F# language or Cω. I also wanted to show in what ways are these features limited in the C# 3.0. I think that thanks to these limitation, the C# 3.0 is still a simple (or at least not difficult) to understand which is very important for mainstream language, but I find it interesting to know what is possible in other (less limited) languages.

Published: Sunday, 15 October 2006, 3:19 PM
Tags: c#, academic, functional, meta-programming
Read the complete article

LINQ extensions - Simplified keyword search

Recently, I came across interesting question at LINQ Forums (Dynamic conditions: How to achieve multiple "OR" conditions with LINQ? [1]). The question is whether LINQ (and especially LINQ to SQL) provides any simple way to return only records that contain one or more of specified keywords in the name. The question looks simple, but it is simple only if you know the number of keywords that you want to look for. In this case you can write following LINQ query:

  // Products that contain "kwd1" or "kwd2" in the name 
var q = from p in db.Products where p.ProductName.Contains("kwd1") || p.ProductName.Contains("kwd2") select p;

The problem with previous code is that you can't use it if the list of keywords is dynamically entered by user (and so its length may vary). Of course, if you want to run query on in-memory data, you can get very nice results by writing extension method called ContainsAny that performs test for keyword array, but if you want to be able to translate query to SQL, the situation is a bit complicated.

Published: Friday, 28 July 2006, 3:57 AM
Tags: c#
Read the complete article

Calling functions in LINQ queries

The LINQ Project [^] is an extension to .NET Framework and most important .NET languages (C# and VB.Net) that extends these languages with query operators and some language features that make it possible to integrate queries in the languages. Thanks to LINQ you can write queries that read data from database (or any other data source). For example, imagine that you want to write set of queries for eshop and you need to perform a price calculation in more queries. The problem with LINQ queries is that you can't simply call a function written in C# that calculates price. The following example is NOT WORKING for this reason:

// function used in filter
static decimal CalcPrice(Nwind.Product p) { return p.UnitPrice * 1.19m; }
// query that uses MyFunc
var q = from p in db.Products where CalcPrice(p) > 30m select p

I think that this is a big limitation, because when you want to keep some more complex logic in the data access layer you should be able to reuse parts of queries that are similar across more queries. The good thing is that with latest release, LINQ became extensible so it is possible to write a extensions that allow this scenario...

Published: Saturday, 10 June 2006, 2:26 PM
Tags: c#
Read the complete article

All blog posts by tag

f# (112), functional (66), research (44), c# (37), asynchronous (27), parallel (23), academic (22), functional programming (20), universe (20), programming languages (18), meta-programming (18), philosophy (15), links (15), presentations (14), data science (12), writing (12), joinads (12), thegamma (11), web (10), data journalism (9), math and numerics (9), random thoughts (9), talks (8), phalanger (8), haskell (7), mono (7), webcast (7), fslab (5), open source (5), visualization (4), fun (4), accelerator (4), design (3), type providers (3), linq (3), f# data (3), .net (3), training (2), coeffects (2), deedle (2), monads (2), art (2), fractals (2), funscript (2), new york (2), manning (2), books (2), teaching (1), fable (1), machine learning (1), comonads (1), fake (1), f# formatting (1), deep dives (1), async (1), events (1), trainings (1), london (1), literate (1)