Rash thoughts about .NET, C#, F# and Dynamics NAV.


"Every solution will only lead to new problems."

Category Informatik

Saturday, 6. August 2016


Fable |> React Native – Native apps with F#

Filed under: .NET,F#,Informatik — Steffen Forkmann at 15:04 Uhr

TL;DR available at the bottom of the post.

“A React Native App is a Real Mobile App”

With React Native, you don’t build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that’s indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React. [project site]

That doesn’t sound too bad, but why do we have to do it in JavaScript?

Well, this article shows that we don’t have to.

The nightwatch app

Consider you are working for some kind of Nightwatch and it’s getting dark and your watch is about to begin.

The nice people of your order gave you a phone and a new app. At the beginning of the night it downloads a list with locations that you have to check. Every location can be marked as OK or you can blow a virtual horn to trigger an alarm. The app also allows you to append an photo of the situation on the ground.

Since many of the locations that you will visit are far away from good internet connection the app stores everything locally on your phone. Once in a while it will sync with the nightwatch central.

So this could look a bit like this:

Nightwatch app

So now after embaressing myself and showing my design skills, let’s jump into the technical stuff.

Developing with F# in VS Code

The app was developed with F# in Visual Studio Code (with ionide and react native plugins). This development environment runs on all platforms, so you can use Windows, Linux or your Mac.

Hotloading F# code

As you can see we have a React Native app with automatic loading of compiled F# code.

The big difference to using JavaScript is that everything is statically typed – even the access to the JavaScript APIs. This gives you nice autocomplete features and depending on the concrete bindings you can even get documentation in the editor:

Autcomplete in F# code

Krzysztof Cieślak did really amazing work with the Ionide – this tooling works pretty well. Take a look at his blog to find out more about the awesomeness that he brings to the ecosystem. He also played an important part in getting React Native to work with F#.

Introducing Fable

Fable is the most important technology behind all of this. It was designed by Alfonso Garcia-Caro as a F# to JavaScript compiler and can do real magic in the browser. Take the time and watch the 10min intro. I can’t stress enough how well this open source project is managed. It’s a real pleasure to be part of it now.

In our case it bridges React Native APIs into F# and also compiles the F# code back to JavaScript whenever we save a file. The React Native framework is listening for the changes in the JavaScript files and swaps the code in the device simulator. There is a lot going on behind the scenes, but it’s already working surprisingly well.

Using JavaScript APIs

Since most of the React Native APIs are developed in JavaScript it’s important to bring these APIs over to F#. This is done as a community effort and the Fable project creates typed JavaScript bindings for many major JavaScript frameworks. This effort is comparable to DefinitelyTyped in the TypeScript world. There is even a tool that can help to convert TypeScript bindings to Fable bindings.

In our case the fable-import-react-native is the most important package. It provides typed bindings to most of the React Native APIs.

This snippet creates a View component in React Native and puts two buttons inside it.

Using F#

One nice benefit of this model is that we can use ordinary, statically typed F# code for our app. In the demo project you can find a small F# domain model:

If you are interested in learning the language then I recommend to look at website of the F# software foundation. For domain driven design in F# you can find excellent articles on a site called “F# for fun and profit“.

Access to native components

React Native allows you to access native phone components like the camera. Most of these APIs are written in a mix of Java/ObjectiveC and JavaScript. Given the Fable bindings are already present it’s super easy to access the same APIs from F#. In the following sample we access a nice ImagePicker via the fable-import-react-native-image-picker bindings:

This ImagePicker is distributed via a separate npm package, but it’s API feels like the rest of the React Native functions. We can provide some properties and a callback – and everything is statically typed so that we have autocompletion in VS Code.

Data storage

For most apps you want to have some local storage in order to cache information. React Native provides a basic abstraction called AsyncStorage that works on Android and iOS. With the help of a package called fable-react-native-simple-store we can use it from F#:

As you can see all function in this storage model are asynchronous and with the help of the async computation expressions they become really easy to use in F#.

Web access

Another advantage of React Native is the huge ecosystem you see on npm. In our app we want to retrieve a list with locations that we need to check. This list is just a bit of JSON on a http resource. With the help of a very popular JavaScript package called fetch and the corresponding fetch-bindings (written by Dave Thomas) we can write something like this:

So we see the same async model here and everything fits nicely together.

Project status

The project with the working title “Fable |> React Native” is currently considered “highly experimental”. APIs and JavaScript bindings are not complete and likely to break multiple times.

In general the Fable project is shaping things up for a v1.0 release. So sharing experiences, comments and bug reports with the Fable compiler and APIs is appreciated.

Debugging of the react native apps is currently only working in the generated JavaScript. With the next release of the VS Code react native extension we will probably be able to set breakpoints directly in the F# source.

That said, it already feels very very productive and if you are interested in this kind of mobile development then check out the sample project and follow how it develops over time. There is even a similar approach that allows you to use F# on fuse, so I think we will probably see a lot of choice in the future.

TL;DR for F# devs

With this model you can start to develop Android and iOS apps on the react native model while still keeping most of the type safety and tooling. Using fable gives you access to a huge ecosystem with JavaScript libraries and frameworks. Check out the sample project and follow the instructions in the Readme.

TL;DR for JavaScript devs

If you like creating apps with the React Native model, but it always felt a bit hard to maintain JavaScript, then this might be interesting for you. With this approach you can apply all your knowledge and use it from a excellent type safe language with amazing autocompleting tooling.

With one or two tricks you can even reuse many of the npm libraries that you know and love. Check out the sample project and follow the instructions in the Readme.

TL;DR for TypeScript devs

You have already left the path of plain JavaScript. Maybe you are ready to leave it a bit further and to investigate different languages like Elm or PureScript. If this is you then check out the sample project and follow the instructions in the Readme. It shows you how a language like F# can help you to work with JavaScript APIs.

TL;DR for C# devs

Sorry, nothing to see here.

Tags: , , ,

Monday, 25. April 2016


“Make failure great again” – a small journey into the F# compiler

Filed under: Diverses,F#,Informatik — Steffen Forkmann at 13:44 Uhr

Giving good error messages is very important for modern compilers. The language Elm is famous for giving excellent user-friendly error messages. Parts of the F# community decided to improve the F# compiler messages as well. We want to make that a community effort and hope many people join us and help to make the compiler emit better error messages.  Isaac Abraham is mainatining a list with possible targets, so if you are interested in helping then take a look at this list.

Unfortunately working on compilers it’s not exactly the easiest task. In this post I want to show you how I tried to improve one compiler warning and hope this helps others to get started.

The task for this post is to improve the compiler warning for the following code:

Currently the compiler shows the following:

Original compiler warning

According to issue #1109 we want to turn it into:

New descriptive compiler warning

As you can see the new message is giving the user more details about the specific situation and also refers to a common error of newcomers.

Please notice that this is probably not the final wording for this warning, but once we have finished this it will be easy to iterate on the concrete warning.

Getting started

The first thing to is to get the compiler code on your machine. I’m using Windows and Visual Studio 2015 here. So what you want to do is the following:

  • Fork https://github.com/Microsoft/visualfsharp on github
  • Start a “Developer command prompt for Visual Studio 2015” in admin mode
  • Run `git clone [your clone url]` and change into the new directory
  • Run `git remote add upstream https://github.com/Microsoft/visualfsharp.git`
  • Optionally: If you want to follow the exact steps from this post, then it makes sense to set your clone to the same commit where I started. You can do that by executing “git reset –hard 8a2e393999f440ea93769a288c37172d98db455a”
  • Run `build.cmd`

This last step will download the internet for you, so don’t be too surprised when you find the lastest “Game of Thrones” episode somewhere inside your packages folder.

Anyways, if everything works then the output should look like the following:

Build works from command line

If the build doesn’t work for you then read the DEVGUIDE very very carefully. If that doesn’t help then please open an issue in the Visual F# issue tracker.

Reproducing the compiler warning

If the build works from command line we should try to reproduce the error with our own freshly built compiler. Let’s open the solution in Visual Studio 2015, set the startup project to “FsiAnyCPU” and hit F5 to start a debug session in Visual Studio. If everything works we will see a F# Interactive Window and Visual Studio is in Debug mode:

Debug works in Visual Studio

Now we paste our code into the command line window:

Original compiler warning

Using the F# Interactive in debug mode is an easy way to do compiler debugging. There are other possibilities (like using fsc.exe), but the F# Interactive allows you to debug the compilation of single lines in isolation from the code above. It’s really neat.

Where to start with hacking

Since we now know how to reproduce the compiler warning, we want to make actual code changes. But where!?

Where??

An easy way to get started is by using the old error message as a search string. When we use Visual Studio’s solution-wide search and look for “This expression should have type” we find exactly two locations inside a file called FSStrings.resx file.

Searching for original compiler warning

So this gives us a new search string “UnitTypeExpected1”.

Searching for UnitTypeExpected1

This looks actually like we found something interesting in CompileOps.fs. Let set a breakpoint and see if it stops when we reproduce our warning:

Debugging

Cool, so this seems to be the place where the warning gets emitted. Now we need to find the place where the discriminated union case “UnitTypeExpected” is created. After another little search we are in TypeChecker.fs:

Type checker

We can try to set another breakpoint and see what happens in that code. The interesting part is the inner else part.

Baby

The code in there looks scary and cryptic at first, but it actually shows the power of using a ML dialect for building compilers. Inside this code the compiler already knows that we want to emit a warning. By pattern matching on the abstract syntax tree (AST) we decide if the left side of the expression is a property. In that case the compiler seem to emit a different warning (see also that code above from CompileOps.fs).

So after hitting the breakpoint and looking in the value of exprOpt I’m pretty sure we are in the right place:

Inspect AST

So somewhere inside that AST we can actually find our name x. Now we have all we need.

Making the code changes

It’s good practice to never make code changes on the master branch. So let’s create a feature branch with “git checkout -b assignment-warning”.

Now let’s start by adding our new compiler warning to FSStrings.resx:

Now we go back to TypeChecker.fs and try to come up with some pattern matching on the AST that finds our special case. After playing around a bit I found:

This doesn’t look super nice, but it follows one of the important rules from the contributor guide – “use similar style to nearby existing code”. We probably want to tidy this up later when initial code review is done. But in the beginning we should stay as close to the original as possible.

Since we decided to store additional data, this already tells us we need to extent the UnitTypeExpected type in TypeChecker.fsi and TypeChecker.fs. After that we can go to CompileOps.fs and use that data:

That’s basically all we need to do. Let’s fix the the remaining errors (don’t worry the compiler will show you all the places) and then reproduce the warning again:

New descriptive compiler warning

Wow. We did it. We actually changed the compiler. And it didn’t even hurt that much.

Compiler changed

Unit tests

Compiler tests (especially if you want to tests negative results like warnings or exceptions) can’t be easily done in standard unit tests. The F# team came up with a different approach where the test runner compiles a .fs file and you can use regular expressions to match against the compiler output.

In order to run the existing test suite call “build.cmd all”.

Are you afraid?

This will take a while, but after all tests are done we should see:

Test results

So good news is we didn’t break anything, but the bad news is that we don’t have tests covering our case. So let’s add one.

We create tests/fsharpqa/Source/Warnings/WarnIfPossibleAssignment.fs:

Now we need to include the test in a test suite. Since there isn’t a good fitting existing suite we need to create tests/fsharpqa/Source/Warnings/env.lst:

And we need to register this new suite in /tests/fsharpqa/Source/test.lst:

Now we can run the test with “src\RunTests.cmd release fsharpqa Misc01” (more details can be found in the TESTGUIDE):

Test failed

So at least we now know that our test gets executed 😉
The concrete test results can be found in a file called 258,259FSharpQA_Failures.log alongside our WarnIfPossibleAssignment.fs:

So it seems we cannot match the same line twice. For simplicitly of this blog post we will go with a reduced test:

Wrapping it up

After we ran “build.cmd all” again it’s now time for the final phase. Commit the changes locally and use “git push origin assignment-warning” to publish your code.
Now go to the Visual F# GitHub repo and create a pull request with an explanation of what you did and what you intended to fix. Often it’s also useful to include one or two screenshots.

Your PR will then go through code review process. Usually you will get a lot of questions and probably you need to change some things in your proposal. This process can take a while so bring a bit of patience.

Anyways, here is my PR for this change – wish me

Good luck!

Monday, 21. March 2016


Property based testing in the real world – or how I made my package manager suck less

Filed under: C#,F#,Informatik — Steffen Forkmann at 16:57 Uhr

A couple of days ago I tried to fix a bug in the .NET/mono dependency manager “Paket“. The bug was a really strange edge case in Paket’s resolver algorithm that resulted in a false positive conflict (an overview about the algorithm can be found here).

In other words: Paket reported a version conflict where it should have reported a valid package resolution.

After some investigation I found that the bug was in some optimization code that tries to cut parts of the search tree. When I disabled that part, the resolver found a valid resolution, but was significantly slower. So after some further testing I came up with a fix that was fast and solved the issue.

But why didn’t we find that edge case before? And most importantly: do we have other bugs in the resolver?

Isaac Abraham suggested to investigate the resolver optimizations further and proposed to use property based testing for this (see Scott Wlaschin’s blog for amazing introduction material).

Problem formulation

In this post I want to evaluate if Paket’s package resolver works correct. Let’s start by clarifying some terms.

  • A “package” consists of a name, a version and a (possibly empty) list of dependencies. In this post we are only talking about meta data. The package contents are irrelevant.
  • A “dependency” is always referencing another package name and defines a version requirement (e.g. >= 2.0 or < 4.1).
  • The “package graph” is a list of packages and acts as a stub for a possible configuration of a package feed like nuget.org. It’s basically a collection of the meta data of all published packages.
  • A “resolver puzzle” consists of a package graph and a list of dependencies. In other words it defines a possible configuration of the package feed and a specific list of package requirements (basically what you would define in paket.dependencies).
  • A “resolution” is a list of packages that “solves” the resolver puzzle. This means all package requirements are satisfied and we don’t have more than one package for a every package name.

Our goal is to show that Paket’s resolver is returning a version conflict if and only if we can not find a package resolution via a brute-force algorithm. We do not compare resolutions, we just want to know if the optimization is missing some valid resolutions.

Generating test data

Property based testing is a stochastical test approach. The test framework (in this case we use FsCheck) generates lots of test cases with random data and tries to automatically falsify a given assumption about the algorithm. 

Usually FsCheck will just generate random, uniformly distributed data for whatever data type it sees. This is a very good default, but in our case this would result in 99% package graphs that have no resolution.

In order to create more sensible data and increasing the likelihood of finding real bugs we need to write our own generator functions.

Let’s consider a very small example and think about package names. If we would use the standard FsCheck data generator then it would generate completely random names including empty string, null and names that contain very special characters. While this is great for testing the validation part of Paket, we don’t really need this here. We just generate some valid package names:

As you can see we just generate non-negative integers and create the package name by prefix a “P”. Similarly we can create random but valid version numbers like that:

Here we just map a triplet of non-negative integers to a version of form major.minor.patch.

Now it’s easy to generate a list of packages with corresponding versions. Actually FsCheck can automatically generate a list of PackageName and Version pairs, but since it’s completely random it would generate a list where most packages have only one or two versions. The following custom generator creates a list of different versions for every package and flattens the result. This has a much bigger chance of creating interesting cases:

With a small helper function that creates random version requirements we can create a full package graph:

The last step is to create some package requirements to that graph that we want to resolve. This is basically what you would write into your paket.dependencies file.

Testing against brute-force algorithm

The following defines a FsCheck property that calls Paket’s resolver with a random puzzle. If the resolver finds a resolution, then we verify that this resolution is correct. If it can’t find a resolution we use a brute-force algorithm to verify that the puzzle indeed has no valid resolution:

This is testing the real resolver against a very naïve brute-force implementation. The brute-force version was relatively easy to write and has no smart optimizations:

And this point I reverted the fix in the optimization code and started the test to see what happens. FsCheck needed about 3s to come up with a random example where a valid resolution exists but Paket’s resolver didn’t find it. That was an amazing moment. Unfortunately the example was HUGE and very complicated to understand.

Shrinking

Most property based testing frameworks have a second important feature called “shrinkers”. While generators create random test data, shrinkers are used to simplify counter-examples and have type ‘a -> seq<‘a>. Given a value (our counter-example), it produces a sequence of new examples that are “smaller” than the given value. These new values are tested if they still falsify the given property. If they do a new shrinking process will be started that tries to reduce the new example even further.

There are two easy ways to create a new “smaller” graph. The first optios is to select a package from the graph and remove one of it’s dependencies and second option is to remove a package completely. The following code shows this:

In a similar way we can shrink a puzzle:

After running the test again FsCheck reported:

The ouput shows that FsCheck generated a random puzzle with 104 packages and reduced it to a sample with only 3 packages and 2 package requirements. This made it pretty easy to analyze what was going on in the optimization part of the resolver. The sample was even smaller than the one that was reported from the wild.

With the fix reapplied I rerun the tests and FsCheck reported another error:

So now FsCheck discovered a new, previously unknown bug in Paket’s resolver. The sample shows 2 packages and one of the packages is requiring a non-existing package.
This is trivial case and the brute-force algorihm is instantly finding a solution. So what is wrong in Paket’s resolver?
Again the answer is hidden in some performance optimization and the fix can be found here.

But this was not the end – the property based test spotted yet another counter-example so I fixed that as well.

Conclusion

It took me a while to build up property based testing for this complex scenario. Most of the time was needed to build custom generators and shrinkers, but I was able to reproduce a bug from the wild and also found two new bugs. I think this is a big success.

Wednesday, 15. January 2014


FSharp.Configuration 0.1 released

Filed under: C#,F#,Informatik — Steffen Forkmann at 13:40 Uhr

As part of a longer process of making FSharpx better maintainable I created a new project called FSharp.Configuration. It contains type providers for the configuration of .NET projects:

Yaml type provider

Additonal information:

Please tell me what you think.

Tuesday, 14. January 2014


FSharpx.Collections 1.9 released

Filed under: .NET,C#,F#,FAKE - F# Make,Informatik — Steffen Forkmann at 11:29 Uhr

I’m happy to annouce the new release of the FSharpx.Collections package on nuget.

Most important changes:

Please tell me if it works for you.

Wednesday, 3. April 2013


A tale of nulls – part I

Filed under: F#,Informatik — Steffen Forkmann at 17:43 Uhr

Triggered by a short tweet by Tomas Petricek and a blog post by Don Syme I had a couple of conservations about null as a value, Null as a type (Nothing in Scala), the null object pattern and the Maybe monad (or Option type in F#). I decided to share my opinion on this topic in order to help others to make their own opinion.

Part I – Null as a value

Unfortunately most programming languages have some kind of null pointer. We are now even at a point where some people claim that Tony Hoare’s famous billion dollar mistake costs actually a billion dollar per year.

But before we start to think about solutions to the null pointer problem let us first see where null values might come in handy.

Uninitialized values

In a statement oriented language like C# it is sometimes not that easy to represent uninitialized state.

As you can see we forgot to initialize peter in the missing "else-branch" which might lead to a NullReferenceException. There are a couple of things we can do to prevent this from happening. First of all we should omit the explicit initialization with null:

In this case the C# compiler throws an error telling us "Use of unassigned local variable ‘peter’".

In expression oriented languages like F# the problem doesn’t exist. We usually write initializations like this:

image

There is no way to forget the else branch since the types don’t match.

Unknown values

Consider a search function which tries to find a Person in a list:

Unknown values are probably the most common cause for the introduction of nulls and in contrast to uninitialized values they have much more global effects.

Solutions to unknown values

1. Using explicit exceptions

One easy solution to get rid of the nulls is to make the exception explicit:

One benefit here is that we have a concrete exception which is telling us what went wrong. Unfortunately nothing forces us to handle this exception in the calling method. This means the program can still crash. Another problem is that if we use try/catch as a control flow statement (i.e. use it very very often) then we might slow down our program.

And there is still a philosophical question: is it really an exception if we don’t have a person in our repository?

2. Using out parameters and returning bools

If we want to make the result of our search a little more explicit we can also introduce a boolean return value:

This is a pattern which is actually used everywhere in the .NET framework, so it must be good right?!

Just a simple question here: What did we gain exactly? If we forget to check for nulls why would we remember to check the bool?

There is another interesting observation here. Due to the introduction of out parameters we also introduce the uninitialized value problem in every calling method, which is bizarre.

3. Null object pattern

“In object-oriented computer programming, a Null Object is an object with defined neutral ("null") behavior. The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof).”

Wikipedia

So obviously this makes only sense in a context where objects have observable behavior. So let’s add some behavior to our Person class:

Let’s look at this solution for a moment.

  • Pro: Implementation of missing behavior is trivial
  • Pro: We don’t introduce null values –> we won’t get NullReferenceExceptions
  • Pro: The name of the class carries information about the reason for the null value
  • Cons: In order to to get rid of the Person(string name, int age) constructor in the null-object we had to introduce an interface
  • Cons: In order to use the interface we had to modify the Person class. This might be a real problem if we don’t have access to the source. We would need some kind of ad-hoc polymorphism like Haskell’s type classes, Scala’s Traits or Clojure’s Protocols (read more about the expression problem)
  • Cons: Everything we want to do with Persons has to be part of the IPerson interface or we have to fall back to explicit runtime type tests, because there is no way to get to the data:

    image

  • Cons: Without ad-hoc polymorphism the Person class is getting more and more complex over time since we are adding all the behavior to it. Compare it with our starting point where it was a simple data representation. We totally lost that.
  • Cons: Errors/bugs might appear as normal program execution. [see Fowler, Martin (1999). Refactoring pp. 261]

Don’t use this approach it’s really not a good solution.

4. The Option type (a.k.a. Maybe monad)

The option type is a way to push the idea from 2. “returning bools” into the type system. There are lots of tutorials about the option type on the web, but for now it’s enough to know that it is something which is based on the following idea:

In order to allow pattern matching in C# we introduce a small helper:

With this idea we can get rid of all null values in the program, we don’t have to introduce an IPerson interface, the null case is type checked and the best thing is it’s really easy to create functions like IsOlderThan12:

Please don’t implement the option type yourself. Even in C# it’s much easier to just reference FSharp.Core.dll and use FSharpx (read 10 reasons to use the F# runtime in your C# app).

Of course this is only the tip of the iceberg. If you read more about the option type you will see that its monadic behavior allows all kinds of awesome applications (e.g. LINQ, folds, map, …).

5. The Either type

One of the benefits of the null object pattern above was that it allows to encode the reason for the missing value. In some cases we need the same thing for the maybe monad. So let’s try to capture the reason in the None case:

Now we can use this in the TryFindPerson method:

As with the option type please don’t rewrite this stuff yourself. There is a Choice type in F# which helps to capture this idea and Mauricio has a couple of blog posts which explain how to use it from C# (of course FSharpx is helping here again).

6. The (singleton) list monad

The option type captures the idea that we can either have one value or nothing. We can do the same thing with List<T>:

Of course this uses only a small subset of the power of IEnumerable<T> but I wanted to show the similarity to the maybe monad. You can read more about the “poor man’s option type” on Mauricio’s blog.

Conclusion

We saw a couple of very different solutions to get rid of null values. Normally I’d only use the option type or the either type (if I need to carry the reason). In some very rare situations (e.g. C# only projects) I would also use singleton lists.

I wouldn’t use the other solutions. They are potentially dangerous, especially if your project gets bigger.

I would be happy to read your opinions.

Tags: , ,

Tuesday, 11. December 2012


Testing, proving, checking – How to verify code properties

Filed under: F#,Informatik — Steffen Forkmann at 13:12 Uhr

As programmers we often want to express that a special property holds for a method, e.g. we want to say that the associativity law holds for list concatenation. In F# we could define a concat method like this:

As programmers we could write a couple of unit tests which try to check the associativity law. With NUnit enabled we could write this:

But the question is: did we cover all interesting cases? In computer science we have a method to prove that the property holds for all lists. This methods is called structural induction (see also this video lecture by Martin Odersky) and would look like this:

1) Rewrite the code as equations
concat ([],ys)    = ys                  [CON1]
concat (x::xs,ys) = x :: concat(xs,ys)  [CON2]
2) Rewrite the property as an equation
concat(concat(xs,ys),zs) = concat(xs,concat(ys,zs))
3) Check the base case
concat(concat([],ys),zs) 
= concat ([],zs) // using CON1 = [] // using CON1
concat([],concat(ys,zs))

= concat (ys,zs) // using CON1
= [] // using CON1
3) Show the inductive step
concat(concat(x::xs,ys),zs) 

= concat (x::concat(xs,ys),zs)) // using CON2
= x :: concat(concat(xs,ys),zs) // using CON2
= x :: concat(xs,concat(ys,zs)) // induction hypothesis
= concat(x::xs,concat(ys,zs)) // using CON2

This math is very clean and shows that the associativity law holds for all lists. Unfortunately even with a slightly more complicated sample this gets at least tricky. Try to prove that reverse(reverse(xs)) = xs with reversed defined as:

As you will see the naïve approach with structural induction will fail (for a nice solution see this video lecture).

There is even a bigger problem with the proof: one assumption of induction is referential transparency of the given functions. We can’t always assume this.

So we can’t always (easily) proof code properties and we don’t want to write too many unit tests – then what can we do?

One compromise solution is to use a tool which systematically generates instances for our tests. There are a couple of tools out there, e.g. there is QuickCheck for Haskell or PEX for .NET. In F# we can use a tool called FsCheck:

Of course a test like this doesn’t prove that the property holds for all lists, but at least it verifies all bases cases and probably a lot more cases than one would manually do.

If you introduce a bug you get a nice report, which even shows a counterexample:

fscheck

It’s even possible to add these tests to your test suite and to run them during the CI build. So don’t stop at classical unit test – check code properties!

Tags:

Tuesday, 18. September 2012


Dev Open Space 2012 – 19.-21.10.2012 in Leipzig

Filed under: Coding Dojo,F#,NaturalSpec,Veranstaltungen — Steffen Forkmann at 7:08 Uhr

Open Source. Open Space. Developer Open Space Nachdem es sich die letzten beiden Jahre mehr und mehr angekündigt hat, wurde der .NET Open Space in Leipzig nun in Dev Open Space 2012 umgetauft. Dies trägt dem Punkt Rechnung, dass die Themenwünsche der Teilnehmer immer breiter geworden sind und wir uns vor allem auch über git, Ruby, JavaScript, HTML5, node.js, CQRS und vieles mehr unterhalten haben. Weiterhin wird es natürlich trotzdem noch reine .NET-Themen geben.

Neu sind außerdem die kostenlosen Workshops die bereits einen Tag vor dem OpenSpace angeboten werden. Ich selbst werde einen zu F# und Test Driven Development halten:

“Test Driven Development (TDD) bringt viele Vorteile für den Code aber erfordert auch eine Menge Übung. Dieser Workshop zeigt, wie man TDD mit F# mittels NaturalSpec and NCrunch erfolgreich einsetzt. NaturalSpec ist ein F#-TDD- Framework, mit dem Unit Tests auf sehr intuitive Weise ausgedrückt werden können. NCrunch hilft, diese Tests ständig (bei jedem Tastendruck) auszuführen. Das zusammen ergibt einen sehr schnellen Feedbackzyklus und TDD wird deutlich schneller. Nach einer kurzen Einführung in die Tools werden im Workshop gemeinsam kleine Programmieraufgaben gelöst.”

Die Anmeldung ist bereits möglich.

https://inlineafarmaci.com
Tags: ,

Thursday, 13. September 2012


Skillsmatter “Progressive F# Tutorials 2012” session in London

Filed under: F#,NaturalSpec,Veranstaltungen — Steffen Forkmann at 15:54 Uhr

I’m happy to announce that I’m giving one of the “Progressive F# Tutorials 2012” in London this year. This event is going to be legendary. Abstract:

Test-Driven Development can give you a lot of benefits for your code but also needs a lot of practice. Come to this session and learn how to master TDD with F#, NaturalSpec and NCrunch.

NaturalSpec is a F# TDD framework which allows to express tests in a very intuitive way and NCrunch helps to execute these tests continuously on very key stroke. This gives a very fast feedback loop and helps to speed up your TDD coding.

After a short introduction of the tools we’ll try to solve a small coding problem together in a coding dojo. All skill levels are welcome and the session will give a lot of room to try out new ideas.

Book your tickets for this awesome event.

Tags: ,

Graph type providers in FSharpx

Filed under: C#,F#,Informatik,Mathematik — Steffen Forkmann at 9:24 Uhr

After the official Visual Studio 2012 launch yesterday I think it’s a good idea to announce two new type providers which are based on the DGMLTypeProvider from the F# 3.0 Sample Pack.

Synchronous and asynchronous state machine

The first one is only a small extension to the DGMLTypeProvider by Tao. which allows to generate state machines from DGML files. The extension is simply that you can choose between the original async state machine and a synchronous version, which allows easier testing.

image

If you want the async version, which performs all state transitions asynchronously, you only have to write AsyncStateMachine instead of StateMachine.

State machine as a network of types

The generated state machine performs only valid state transitions, but we can go one step further and model the state transitions as compile time restrictions:

image

As you can see the compiler knows that we are in State2 and allows only the transitions to State3 and State4.

If you write labels on the edges of the graph the type provider will generate the method names based on the edge label. In the following sample I’ve created a small finite-state machine which allows to check a binary number if it has an even or odd number of zeros:

image

As you can see in this case the compiler has already calculated that 10100 has an odd number of zeros – no need to run the test Zwinkerndes Smiley.

This stuff is already part of the FSharpx.TypeProviders.Graph package on nuget so please check it out and give feedback.

Tags: , ,