Back to Home

About F # for architects

F · multithreading · LOP · asynchronous programming · .net 4.0

About F # for architects

Original author: Chris Smith
  • Transfer
This article grew out of a report made by Chris Smith, one of the developers of F # at the DevLink conference. In general, it is of an overview nature, but despite this, and the fact that with the efforts of shwars , mezastel and partly your humble servant, F # has repeatedly flashed on Habré, I think that this programming language has not become so obvious to everyone that this article is completely lost meaning. Moreover, here Chris is trying to answer the main question, which, I think, torments everyone who has ever heard of F #. Where is it to apply it? Whether he succeeded or not is up to you to judge. I hope after reading you at least something about all this will become clear. If so, I will consider my mission exceeded :)
PS The first translation, so do not blame me for some possible bugs.
image

After the appearance of F #, of course he is surrounded by a lot of emotions, but the question that most people at the same time is concerned with - why do I need this? I think we can assume that F # is something good, because otherwise Microsoft would hardly have spent so much time and effort putting it in the new Visual Studio 2010. [Note. perev. Is a weak argument :)]

Therefore, below we will try to abstract from many emotional statements uttered in conversations about F # and look into the eyes of facts. I'm not going to convince you to start programming in F #, but instead I’ll say what this language is good for and let you decide for yourself if it’s worth your attention.

If you program in C # or VB.NET and are immensely happy at the same time, then most likely you have no reason to learn F #. Just stay happy. ;) But if from time to time you are forced to struggle with your own .NET code, then maybe F # is just what you were waiting for.

Gossip


There are a lot of rumors about F #. Here is some of them.
  • The code you are currently writing in C # will be deprecated tomorrow. - Not true. F # is not going to replace C # or VB. F # is just different, so some things are easier to do on it, and some more complicated. The point is that with F # you have a choice. And below we will try to identify some of the situations where F # may be preferable to C #.
  • In F #, you can parallelize code for free. - Not true. Although F # (and other NSFs) make it easier to parallelize code, it doesn’t do this for nothing. Generally speaking, you can write the same locks or races in F # as in C #. The advantage of F # is that you have to clearly aim the gun in the leg first. (Note perev .: allusion to the side of the old programmer's joke about how the task of shooting himself in the leg is realized in different languages .)
  • For functional programming, the future is not true. Functional programming languages ​​are becoming objects of increasing attention today - Erlang, Scala, Nemerle, Haskell, etc. However, the key ideas of functional programming have been around for a long time. And I do not think that functional programming will become the main and only paradigm that everyone will switch to. Rather, in my opinion, this is a good way to solve a specific class of problems. F # is a hybrid language, and it allows you to write code in the paradigm that best suits the current task.
  • F # programmers look smarter and better than others. - True. Absolute.
  • You should rewrite all your ASP.NET applications to F #. - Not true. In a keynote address at DevLink, Josh Holmes especially emphasized that this is a bad idea. It's not that the F # + ASP.NET bundle itself was a bad idea, but the desire to use new technologies just to use new technologies makes things harder than they should be.

To summarize the above: you need to understand what F # is, and if using it will make your work more efficient, then use it. If not, use what you already know.


Tongue


  • As I noted above, F # is a multi-paradigm programming language. You can write functional, imperative and object-oriented code in it. This allows you to be more pragmatic, instead of trying to push any task facing you into the Procrustean bed of classes and interfaces.
  • F # uses type inference, which leads to more concise programs. Think about how much time you spend adding type signatures, semicolons, curly braces in your favorite PL. All this information is just crutches that make writing a compiler easier. Why not write the code you want and let the compiler calculate the rest? You will see later why I consider the laconicism of F # its main strength.
  • F # is a .NET programming language. It compiles in IL in the same work cycle as C # with VB and will easily work with existing .NET code.

Instruments


  • F # is included in the standard Visual Studio 2010 suite, although it is present now, as a plugin for VS2008.
  • It has an interactive programming environment ( REPL ) for both Ruby and Python, called the F # Interactive Window.

Of course, it is very easy to wallow in the whole variety of details of a new programming language.
The only thing I ask you to remember about F # as a whole is that it is fun to program on it. F # breaks down many programming barriers and lets you concentrate on writing the code you need.

It is important to note that F # supports almost all the features that C # has. Therefore, you can use it without fear of the principle of "all or nothing." You do not need to throw away existing code and translate everything into F #. In general, we expect F # code to be mainly used as class libraries integrated into a large software product. Perhaps some database server components will be written in F #, while the rest of your code will remain in C # / PHP / Smoke Signals / whatever.


The ability to seamlessly interact with .NET opens up many possibilities for F #. You can not only use the strengths of existing tools, such as the VS debugger, IntelliSense, but also other .NET platforms, for example, use XNA to run the F # code on XBox, or Silverlight to launch it on the network. This synergy is probably the main reason that F # gets a lot more attention than earlier programming languages ​​like OCaml. OCaml is great, but does it come with a world-class debugger, visualization libraries, and an ecosystem formed by the development community?

But still, why learn this new language?

Let's start by looking at some terms related to F #.
  • Statically typed. F # is a statically typed language, unlike, for example, dynamically typed Ruby. This means that type information is known at compile time. Therefore, although you can’t do some things, such as monkey patches , the code runs much faster and you can learn about most errors even at the compilation stage.
  • Laconic. In addition to type inference, F # also uses significant spaces. If you shift the lines under the if-construction several spaces to the right, the compiler will regard them as the body of the operator. This eliminates the need to clog your code with curly braces and saves you vertical space. Less code on the page means that you can see most of the program at the same time, and less context switching while viewing the code. It may not sound too grandiose, but in fact it will be of great help to your effectiveness.
  • Expandable. It's not about data centers and web servers, but that if you apply the holistic principles for software development to your F # code, you can write enterprise-level applications on it. (Simply put, F # is not just a language for one-time utilities.)
  • Researched. In F #, you don’t have to go to design to understand how everything works. You can quickly prototype F # solutions, as well as experiment with algorithms and approaches using the F # Interactive Window. Based on the concise nature of F #, you will not write much code to experiment with your programs.
  • Libraries F # comes with its own library for writing functional code and much more.

Functional vs Object Oriented


Functional programming has been known since the 1950s (LISP) - so why is it so important now? Many will say that things like immutability help write multithreaded programs, which in my opinion is not so important. Because if you want to seriously engage in multi-threaded programming, there are PLs created specifically to do this and only that.
The main advantage of functional programming lies in what is called small programming .
What determines the current state of software development? - OOP. The main way in which we solve the problem of converting the algorithm into code is to break it into objects, effectively model the subject area using classes and their behavior. It -programming in general . The abstraction process works great for modeling large systems and breaking them down into smaller and lower levels, but ultimately you will hit the wall.
What about the bodies of the methods? The real code that is enclosed in the classes? This is programming in small. The problem with OOP is that when you write code of an algorithmic type, it makes no sense to create classes and interfaces. When you program in small, all you really do is transform the data and do the calculations.
Imagine that OOP is a baseball trap. It is well suited to catch a baseball, but far from convenient to catch a soccer ball. To do this, you need your fingers to move. Functional programming and describes the essence of programming in small. It focuses on data manipulation, which you want to do without troubles with classes and a given type hierarchy.

Areas of use



The first area in which F # is truly unsurpassed is technical and quantitative programming, i.e. in complex mathematical calculations.

Simulation


Simulation is one area that F # fits well with. Imagine that you are writing some kind of physical simulator, or trying to simulate some realistic situation. In F #, you can neatly write the functions you need without having to draw code abstractions to real-world processes.
Another aspect of simulations that makes F # a good choice for them is the unit . You can encode units such as feet or meters per second into the current F # type system. After that, you will get a compiler warning if you try to add acceleration to speed. This allows you to protect yourself from a number of bugs.

Computational Finance


Some of the very first firms to use F # were in finance computing. These firms have large databases for automated trading on stock exchanges, calculating risks, etc. (Just the kind of computerized finance that caused the current global economic crisis :)) F # provides these investment companies not only with a way to express their financial models in a simpler and more declarative form, but also integrate with the rest of their applications through .NET interaction. (For example, sending intensive computing to several machines through a COM service, and stuff like that)

Large-scale data processing


Finally, F # does a good job of data mining. For example, imagine you are trying to extract some customer information in order to recognize trends. In F #, you can simply work with your data in the F # Interactive Window, and there is no need to litter your machine with dozens of one-time projects. Also, using the concise programming model F # the cost of error - refactoring or rescheduling your approach is significantly reduced.


Language Oriented Programming


The next item is NLP , which means blurring the boundary between YP and natural languages. (You can read more about using F # in JOP in this article by Chris )

Writing Parsers


If you want to be advanced in domain-specific languages, why not go ahead and write your own parser? And the F # PowerPack library has FSLex and FSYacc, two great tools for creating parsers. In fact, the F # compiler parser was created using FSLex and FSYacc.

Extensible F # Code


Another great example of JOP is the use of the computational expressions that are available in F #. This is a powerful language feature that allows you to write normal F # code and customize the way it is executed. For example, suppose you want to write some F # code to interact with a robot on Mars. Instead of writing tons of boilerplate code to try again to send every command you send to an all-terrain vehicle - for example, in the case of space obstacles or Martian uprising - you can write a computational expression (the so-called F # Workflow) to automatically restart any F # code times until a certain point, or until it succeeds.
(This is a rather complicated topic, which actually needs to be devoted to more than one article)

Create new languages


Another area in which F # is excellent is the creation of internal domain-specific languages ​​(DSL, mini programming languages ​​embedded in your code). Marked associations make the process of creating abstract syntax trees (or any other tree-like structures) very simple.

Expression trees


Finally, F # has Expression Trees, just like C # and VB.NET. This allows you to get a "compiler-generated" form of F # code, which, coupled with suitable libraries, can allow you to give the program execution to other platforms. For example, to an SQL server or GPU of your video card.

Multithreaded programming


F # is also good at multi-threaded programming, to be more precise: in parallel, asynchronous, competitive and responsive programming domains. F # does not parallelize your code automatically, and does not have any built-in support for parallel primitives. Instead, it has several features that make parallel programming easier. But not one of them is a silver bullet.

Immutability by default.


In F #, as in most other NSFs, data is immutable by default. Therefore, if your program is in a pure functional paradigm, you will not have any problems with racing when executing multiple threads, since there is no shared mutable state for two competing threads.

Parallel Extensions in .NET


Generally speaking, this functionality applies not only to F #, but to all .NET. A long way to make writing parallel programs easier has been the implementation of the Parallel Extensions (PFX) library in the fourth version of the .NET. Although PFX provides many great features for the .NET platform, there are two things that I especially liked.
Task Parallel Library (TPL) - a set of classes for abstracting the process of placing the "tasks" of the program. With TPL, you can forget about the need to manually place tasks and manage threads. Instead, you can trust TPL. He will do this for you, he will adjust the number of running threads to be sure that you will not overload the system with parallel tasks.
Another, and perhaps even more remarkable part of PFX is Concurrent Data Structures. This is a new set of collection types that are specifically designed to work with high-performance multi-threaded applications. Therefore, instead of controlling all the details of a shared mutable state, you can just let both threads write to one of these competitive structures, and all the dirty work with lock-unlocks will no longer bother you.

Asynchronous programming

(in detail msdn.microsoft.com/en-us/library/ms978405.aspx )
You may have heard somewhere before that F # makes asynchronous programming very easy - this is absolutely true.

In order to write asynchronous programs in .NET, you must use the Asynchronous Programming Model (APM). This is a template in which you start an asynchronous operation, for example, reading from a file, calling BeginOp (i.e. BeginRead) and sending a callback. When the asynchronous operation completes, a callback is executed in which you must call EndOp (i.e. EndRead).
Although this approach faithfully served .NET for nearly a decade, it is damn frustrating to deal with.
  • Passing states via callback is tedious and provokes errors
  • It’s not so easy for you to catch and handle exceptions if your code is spread out among myriad callbacks.
  • and. etc.

The slide above shows code from a group of developers from Microsoft Patterns and Practices, and is the recommended way to process a series of pictures in multi-threaded mode. In any case, it should be noted that there is a lot of code that does not look too simple.

And so you can write the same program in F # using the F # Asynchronous Workflows library. As I have said many times, F # was not created specifically to write multithreaded programs. F # Asynchronous Workflows is just some of the functionality built into the F # library that makes asynchronous programming very easy. It is enabled through F # Computation Expressions.
In this code you can see 'let!' and 'do!'. F # Asynchronous Workflows performs this operation asynchronously, doing all the activity with skipping through threads and callbacks overs.

disadvantages


So, I told you a lot about how wonderful F # is, but let's get back to reality. You do not believe that F # is a continuous fairy tale?

F # is not suitable for everything, here are some of these areas.

Presentation layer


In F # 1.0, we are not going to provide any code generators. Therefore, you cannot use any WYSIWYG editors from WinForms or WPF. If you want to write a presentation layer in F #, you will, unfortunately, have to do it all by hand. However, this is not the end of the world due to the .NET involvement of F #. You can simply create your UI in C # and call your F # code through class libraries.

Object Oriented Hierarchies


Even though F # allows you to write object-oriented code, this is not the main paradigm of the language, so writing complex OO code may look a little strange. F # also supports many functional constructs that do not support C # and VB, such as labeled associations and function currying. Therefore, if you create a library in F # that exposes “functional” code, it will be incorrect if you try to use it in non-functional languages.
The main thing here is to properly encapsulate your F # code, programming in small, when you want to integrate it with a large component, programming in general.

What to do next if you decide that F # is suitable for some part of your application? Should you care about hiring a group of outrageous “nuclear physicists”? Not. I can only repeat myself and with all my heart shout a loud “NO!”. F # - not just for eggheads! For example, this summer we hired several intern graduates to work on some examples of F #.
Functional programming is essentially nothing complicated, it simply considers tasks from a different perspective. The main thing is to be careful about the statements of your programmers when they learn F #.
  • "It's almost the same as C # . " This means that they are not using it correctly. The whole point of F # is that it offers a different way of thinking about programming, and in this, another approach, it’s more efficient. If you write C # code in F #, you won’t gain anything.
  • "F # is too simple for real tasks . " Although F # is easy to learn, you can achieve quite a lot, even if you write simple functions.
  • "Functional programming takes out my brain . " This means that you are on the right track. Learning F # opens up other approaches to solving problems.

Support


Although F # can help you write more productive code today, the question is, how easy can you handle it tomorrow? What are the costs of maintaining F # code in the long run?
One of the main advantages of F # is that it is short. I have already noted this before, but I will say it again: when you debt the code, the ability to see all the code related to the problem on the screen eliminates the need to constantly switch context between different code files.
It can be said that hallucinogenic functional code is more difficult to understand than the more ordinary imperative. This, of course, is true, but the truth is that you should not write hallucinogenic code in the first place. (Just like there is no such need for any other programming language). The idiom code in F # is clear and readable. Of course, you can use many features of the language, for example, composition of functions and currying, without complicating the code too much.

Conclusion


In conclusion, I repeat: if you really like to use C # or VB, just use them further. You can benefit from learning F #, as well as learning any other language, but don't switch to F # unless there is a specific reason.
But if it seems to you that your language does not allow you to fully express your ideas, clogs up your code with unnecessary syntax garbage, which makes no sense, try F #. In areas related to a large number of calculations or data transformations - technical programming, NOP, parallel / asynchronous - you can get significant benefits.
Writing code in F # will not make your programs, as if by magic, faster or less resource intensive. All that he does is gives you the opportunity to look at the problem from the other side, with which its solution can turn out to be more effective, and simply increases the number of ways for expressing your ideas.
So, if you haven't installed F # yourself, you can do it right now: fsharp.net
Linux developers can work with F # in Mono. mono-project.com

Read Next