tags:

views:

1532

answers:

8

Does anyone have any practical examples where F# would be a better choice than C# or VB.NET? Please can you demonstrate using source code?

A: 

Async computations and math are easier in F# but I wouldn't choose it to implement a complex UI.

Darin Dimitrov
Why not? The tools are not there yet, but F# support OO paradigm as well.Also look at GUI using reactive programming.
Dave Berk
@Dave Berk, in terms of building and managing a GUI, C# tends to be more expressive. GUI code tends to require a lot of state management, which can be done using F#, but the language itself doesn't make it as easy as C# or VB. I think @darin's assertion is correct just as I would say that I wouldn't choose C# to do math intensive asynchronous business logic. You should pick the language that makes the task the easiest.
Michael Meadows
Could you elaborate on how F# doesn't make it as easy? having to write "mutable" all over? Or "val" needing the DefaultValueAttribute? F# will be more verbose on some mutable things, but I think from type inference alone, you'll gain it all back.
MichaelGG
Depends what kind of GUI.
Jon Harrop
I would say that state management in F# isn't inherently any more difficult than in C#, but it also isn't inherently much less difficult, and if you're more experienced in C# the practical benefits from that may outweigh any inherent advantages of either.
Max Strini
+24  A: 

Your question could be answered more broadly, since you're really asking when you should use a functional programming language versus a procedural language.


Functional languages (F#) are well suited for applications that need to run in parallel. Logic that is mathematically intensive are good fits. Also, any type of logic that involves matching and/or transforming data/patterns. Good examples of functional languages other than F# that you might be familiar with are SQL and XSL. These types of languages rely on stateless set operations over explicit procedure calls.

In metaphorical terms, the type of real world activity that resembles functional programming is working on a factory floor. While each station (function) has a sequential set of steps (procedures), the station itself must be unchanged by an item as it passes through. Also, an item cannot be operated on unless it matches the type of object that the station is designed for.

Note that the above metaphor isn't perfect, since the items will have their state changed by the station. It would be a better fit if the station received an item and then created a new item based on the original plus any work it did. Additionally, the items wouldn't travel on a linear assembly line, but would instead be constantly "matched" to a station after each previous station completes its work. Unfortunately, I can't think of a perfect real world metaphor, but with these modifications, you can imagine how it might look.


Procedural languages (C# and VB) are better for the type of logic that tends to be more workflow oriented, where multiple sequential steps are required to execute a workflow. If your logic requires building state from a single or multiple method calls, procedural languages are a more natural fit.

A methaphorical example of procedural programming is getting ready for work. From the moment you wake up until you get in your car, you are executing steps that contribute toward your end state. What you do may branch (and this is the key difference that I'll explain below) depending on conditions, for example if you run out of toothpaste, you open a new box).


The key difference is that functional programming limits procedural code to that which does not cause side-effects (state change). Instead, it relies on matching patterns to handle variations. Procedural programming, on the other hand, relies on branching and looping structures to manage variations.

Michael Meadows
+1: Helpful explanation.
Moayad Mardini
Nice. I like the mention of SQL/XSL as popular examples of functional languages.
Brian
+1 for the helpful explanation too, but that factory floor metaphor seems wrong to me. Don't factory stations typically operate on mutable objects?
Jeff Sternal
@Jeff Sternal, You're right. I was trying to think of a better metaphor. In the case of the factory, you'd have to either return a new object, or create something that is appended to the item. I'll think of something better and revise.
Michael Meadows
I think a coin sorter is a much better example for the functional metaphor, though it's still not 100% accurate. It's possible there's nothing in the physical world that's exactly the same. Perhaps DNA?
Scott Whitlock
+4  A: 

F# is much closer to a pure functional language. It has constructs and features geared towards maximizing your productivity and capability when using a functional programming style. This include features like:

  • enforced immutability of values
  • pattern matching for function invocation
  • concise syntax focusing on transformative operations
  • structural concepts like tuples and mappings
  • list and set manipulation syntax
LBushkin
In fact, it is a functional programming language, where C# isn't at all. I've seen it almost is the same as Haskall, though there are differences.
Dykam
...although C#3.0 does contain several new functional programming features.
Robert Harvey
@Dykam I suggest you read /a lot/ more about Haskell and F#, because if you think they are "almost the same", you have absolutely no idea what Haskell is.
Rayne
+11  A: 

Type inference does not suck. When you use lots of generics, the C# method signature is sometimes bigger than the method itself:

public static IEnumerable<U> Map<T,U>(Func<T,U> f, IEnumerable<T> e)
{
    foreach (var x in e)
    {
        yield return f(x);
    }
}

In F# it's just

let Map f e =
    seq {
        for x in e do
            yield f x 
    }

and I can see the inferred type by hovering my mouse over 'Map':

Map : ('a -> 'b) -> seq<'a> -> seq<'b>

This is a trivial example, but it shows off one thing I like about F#. In C# you're unlikely to write 'highly generic' code because you get swamped under by type annotations.

Brian
I can call map without all the hassle if you invert the two arguments and prepend the first one with this to make it an extension method:someArray.Map(x => x.ToString());
Dykam
My point was about the hassle of authoring the method in the first place, not calling it. Regardless, it's a trivial example - you'd never write this, since it's Seq.map in F# (or Enumerable.Select in C# or VB)... the point is just to call out that type inference is your friend.
Brian
True, but isn't method declaration a minor thing? I normally don't care too much about it. But I admit it has a more bloated look, which I call explicit type inference.
Dykam
It's a minor thing, until you start doing lots of generics and it becomes a major thing. See http://stackoverflow.com/questions/196294/what-is-a-catamorphism-and-can-it-be-implemented-in-c-3-0 and look what a mess the C# becomes. (Equivalent F# code had 3 less-than characters for generic types, whereas same C# code had more than 60!)
Brian
Had to double check and make sure I didn't write this answer. It is spot on. In normal code -- i.e., nothing related to type theory, just trying to write some simple production code -- I had 300 character field definitions. That just wouldn't happen with F#.Not to mention, once you start using Func<>s all over, it just gets horrific.Just for type inference alone, F# is worth it over C#.
MichaelGG
+3  A: 

You might check out

How does functional programming affect the structure of your code?

which talks a little about how e.g. algebraic data types and pattern matching often mean you don't need the cumbersome Visitor design pattern for processing tree-structured data, (indeed many OO design patterns 'disappear' when functional programming is brought to bear).

One shorter code example (called out in the article above) is

http://weblogs.asp.net/esanchez/archive/2008/09/18/point-distance-imperative-vs-functional-style.aspx

which shows how a functional style contributes to succinctness (and often collaterally, correctness).

Brian
+2  A: 

If you want to author an embedded DSL, you'll find F# superior to C# or VB for a number of reasons, including both language syntax (e.g. curried functions, function application through mere juxtaposition (no parens necessary), top-level naming/programming/scripting) and homoiconicity (through F# reflection).

Brian
And don't forget FsLex/FsYacc for *really* custom DSLs.
Juliet
+2  A: 

If you're fond of scripting and you want to program interactively through a REPL, you can do that today using F# inside Visual Studio (but cannot with C# or VB in VS).

Brian
+2  A: 

Split your project into several assemblies and try to write one or more of them with F#.

I started one project that consists of client and server component. Client application is WPF written in C#. Server component is divided into multiple assemblies. Two of them are F#, rest are C#.

Functionality in those two F# assemblies is divided like this:

  1. message parsing and number crunching library
  2. async tasks (reading data from multiple sources - http, ftp)

Some interesting resources to check:

  1. Microsoft F# Developer Center
  2. F# presentation by Luca Bolognese. It is really good and worth watching.
  3. StackOverflow question: Learning F#
zendar