Introduction

A couple of weeks ago my friend Ian Russell explained the decorator pattern at work. For those who don’t know exactly how it works, the decorator pattern allows us to add behavior to an individual object without affecting the behavior of other objects of that class (Wikipedia).

The object oriented solution

There are a couple of typical implementations of the pattern in C#. The “lightweight” version is “just” to create decorators implementing the same interface of the decorated class, and passing the decorated object in the constructor of the decorator. So we need, at least, to create a new interface (maybe not needed anywhere else) and implement a different class for each decorator. Another option is to create an abstract class defining the decorator (that implements the same interface than the decorated object) and subclass it to create the different decorators. As you can imagine, a lot of boilerplate there.

The functional way

Let’s see how we can implement that using a functional language as F#.

Let’s start defining the object that we’re going to decorate:

1
2
let consoleWriter message =
    printfn "Console writer -> %s" message

Is a simple function that prints a message. Let’s decorate that function with a function that logs the message:

1
2
3
let loggingWriter logger writer message =
    logger message
    writer message

The function is like a mix between the class receiving a logger and a writter as a constructor parameters and the function to write the message itself in the object oriented implementation.

Now we need to write the logger. As usual, it will be a function:

1
2
let consoleLogger message =
    printfn "Console logger -> %s" message

And now, let’s create a decorator to add a simple validation:

1
2
3
4
5
let emptyStringValidator writer message = 
    if System.String.IsNullOrWhiteSpace message then
        printfn "Validation error"
    else
        writer message 

One more time, instead of having a class that receives the writer as a constructor paramenter and have a function to write the message, we just have a function that receives the function and the message.

Now it’s time to glue all this functions together. We are going to take advantage of partial application to define a function that uses all the previously defined functions:

1
let decoratedWriter = emptyStringValidator (loggingWriter consoleLogger consoleWriter)

If we take a look at the function signature we can see that it is:

1
string -> unit

So, it’s a function that takes a string (in this case the message) and returns unit (because we are using printfn). Using partial application we have composed a couple of functions: the first one, the one between parenthesis, is a writer (in this case a logginWriter) that takes the consoleLogger and the consoleWriter as a parmeters, and have a free parameter (the message). So, its a function that gets a string and returns unit, that is the function type that the emptyStringValidator is expecting as its first parameter. So, we can pass this function to the emptyStringValidator and we’ll get the function that we want, that takes a string as a parameter and return unit.

If we call this function with a string, we get the following result:

1
2
3
decoratedWriter "Hello world!"
> Console logger -> Hello world!
  Console writer -> Hello world!

And if we call it using an empty string we get the follogins result:

1
2
decoratedWriter ""
> Validation error

Summary

We have seen how much more elegant our code results when using a functional language. In the object oriented code, we have a lot of code that is not really adding any value (interfaces, abstract classes, constructors…). In the functional code, we just have functions and we use a well know feature of the language as it is partial application to compose the function that we really want. You can find the code on Github

In the previous article we saw how to send forms using Suave.Experimental as view engine. In this article we’re going to use Suave.DotLiquid as view engine. We’ll see how we’re going to be able to reuse most of the work done previously.

Suave.DotLiquid

DotLiquid is a port of the Ruby template engine Liquid. Suave is able to use this library thanks to the pakage Suave.DotLiquid. So, the first thing we need to do is install these packages in our project.

Reusing code

We’re going to change only the view part of our application, so we dont need to define any new ViewModel or anything.

The view

To use DotLiquid we need to create temlates as html files. Inside this templates we are able to write constructs that we’ll be replace by text. In this simply example we’re not going to use anything more sophisticated than this, but you can refer to the original documentation to see what you can do.

So, the view should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
    <head>
        <title>Forms with DotLiquid</title>
    </head>
    <body>
        <div>Create</div>
        <form method="POST">
            <fieldset>
                <div class="editor-label">Name</div>
                <div class="editor-field">
                    <input name="Name"type="text"required=""/>
                </div>
                <div class="editor-label">Surname</div>
                <div class="editor-field">
                    <input name="Surname"type="text"required=""/>
                </div>
            </fieldset>
            <input type="submit"value="Create human"/>
        </form>
    </body>
</html>

In this is standard HTML. Let’s take a look at the view that will display the Human model to see DotLiquid in action.

Forms with DotLiquid
Show
Name:
Surname:

As you can see, we are accessing the properties Name and Surname of the model, in this case the Human type defined in the previous article.

The application

The changes we need to do in our App.fsx are really small.

Firts, let’s define the folder where DotLiquid will search for the templates.

1
DotLiquid.setTemplatesDir (__SOURCE_DIRECTORY__ + "./Templates")

And now let’s define the new WebPart we’re going to use.

1
2
3
4
5
let dotliquidHuman =
    choose [
        GET >=>  DotLiquid.page ("CreateHuman.html") ()
        POST >=> bindReq (bindForm Forms.human) (fun form -> DotLiquid.page ("ShowHuman.html") form ) BAD_REQUEST
    ]

As you can see, is very similar to the Experimental one, but we change a little bit how we call the view engine. In this case, we use the function DotLiquid.page, passing as arguments the name of the template and the model to use (unit in the first case, and form in the second case).

And that’s all, we don’t need to make more changes to make it work.

Summary

We have seen how easy is changing our view engine when working with Forms. We’ve seen a very little introduction to DotLiquid, a nice template engine we can use with Suave. You can get the full solution here

Sending data to a web server is a very common task when developing a website. From registering a new user to filling some personal details in a web commerce application, we usually have to deal with filling a form and send its data to the web server. In this series of articles, we are going to see how to send data using different view engines.

Suave.Experimental

Experimental is a component available via NuGet that allows us to write the views using F# code. We are not going to discuss if that’s a good thing or not, we are just going to show how to work with forms.

We are not going to explain how to setup a basic Suave application. Plese refer to their website to do it.

Defining the form

Let’s start creating a new file called Form.fs with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module FSharpForms.Forms

open Suave.Form

type Human = {
    Name : string
    Surname : string
}

let human : Form<Human> = 
    Form ([ TextProp ((fun f -> <@ f.Name @>), [])
            TextProp ((fun f -> <@ f.Surname @>), [])
            ],
        [])

In this file we are defining the type that we want to be filled by the user, in this case a Human with a Name and a Surname. We are defining a Form of that Human as well, specifying the type of the properties, in this case strings both of them. The empty list that you can see at the end of the definition of each field is a list properties (maxLength, min, max, etc). In this basic text, we don’t need any property. The final empty list is a list of ServerSideValidation which is basically a tuple composed by a function that returns an string and a message.

The view

Let’s define the view right now. Let’s start defining the module and open the necessary modules.

1
2
3
4
5
6
7
module FSharpForms.Views

open System

open Suave.Html
open Suave.Form
open FSharpForms.Forms

It’s time to define the view. We should write a code like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
let createHuman = 
    html [
        head [
            title "Forms with Experimental"
        ]

        body [           
            div [text "Create"]            
            
            tag "form" ["method", "POST"] (flatten 
                [
                    tag "fieldset" [] (flatten 
                        [
                            divAttr ["class", "editor-label"] [
                                text "Name"
                            ]
                            divAttr ["class", "editor-field"] [
                                input (fun f -> <@ f.Name @>) [] Forms.human
                            ]
                            
                            divAttr ["class", "editor-label"] [
                                text "Surname"
                            ]
                            divAttr ["class", "editor-field"] [
                                input (fun f -> <@ f.Surname @>) [] Forms.human
                            ]
                        ])
                        
                    inputAttr ["type", "submit"; "value", "Create human"]                
                ])
        ]
    ]
    |> xmlToString

As you can see we use helper functions to write the html tags. Almost all the tags are part of the Suave.Html module. The only one that belongs to Suave.Form is input. Input takes a quotation expression as its first parameter to know which field of the Form is linked to. As last parameter, it takes the form.

We should return an string, so we use xmlToString at the end.

The application

Is time to go to our Suave application and make all this code work. Let’s start defining the WebPart that we are going to use

1
2
3
4
5
let experimentalHuman =
    choose [
        GET >=>  OK (Views.createHuman)
        POST >=> bindReq (bindForm Forms.human) (fun form -> OK ( Views.showHuman form) ) BAD_REQUEST
    ]

It’s a quite simple WebPart. We’re using choose to differentiate between a GET and a POST (we are using the same Url for both actions). In the GET route, we are returning our recently created view. The most interesting part comes in the POST route, where we are binding the information of the POST request to an instance of the Forms.Human type. To display the results we are using the following view:

1
2
3
4
5
6
7
8
9
10
11
12
13
let showHuman human = 
    html [
        head [
            title "Forms with Experimental"
        ]

        body [           
            div [text "Show"]
            div [text (sprintf "Name: %s" human.Name)]
            div [text (sprintf "Name: %s" human.Surname)]
    ]
    ]
    |> xmlToString

As you can see, we only need to access the fields of the Forms.Human type.

Summary

We have seen an introduction to Forms in Suave. In following articles we’ll see how to do the same with other view engines. You can get the full solution here

As Scott Wlaschin points out in his excellent article function composition it’s not the same as using the pipeline operator.

The definition of the pipeline operator is this one:

1
let (|>) x f = f x

So, take the thing on the left hand side of the operator and use it as the last parameter on the function in the right hand side.

On the other hand, we have this definition for the forward composition operator (»)

1
let (>>) f g x = g ( f(x) )

That means, take the parameter and pass it to the function on the left hand side of the operator, and then apply the function on the right hand side of the operator to the result.

For example, if we have this couple of functions:

1
2
let add1 a = a + 1
let mult2 a = a * 2

We can define the composite function as

1
let addAndSum = add1 >> mult2

And therefore, when we do

1
2
let res = addAnSum 3
> val res : int = 8

As you can see, we are applying the first function (add1) to 3 and then apply the second function to the result ( ( 3 + 1 ) * 2 = 8 )

Preparing my talk at FSharp eXchange, Visual Studio Powertools warn me about replacing a pipeline by a function composition. The code (simplified version) is this one.

1
2
3
let tuples = [|("a", [|1|]);("b", [|1;2|]);("c", [|1;2;3|]);("d", [|1;2;3;4|])|]
tuples
|> Array.sortByDescending(fun m -> snd m |> Array.length)

Let’s decompose this code to see what is it doing. The previous code is equivalent to the following one:

1
2
tuples
|> Array.sortByDescending(fun m -> Array.length(snd m))

Looking at the part in the right hand side of the arrow we can see that this is equivalent to the definition of composition we’ve seen previously, being Array.length equivalent to g and snd equivalent to f. That means that we can change the previously code by this one:

1
2
tuples
|> Array.sortByDescending(snd >> Array.length)

As you can see, the final code is much more elegant and succint, and easier to read when you understand what is it doing.

Spain and Germany are dominating with an iron fist last Champions League editions. After a lot of investment, a Premier League team is ready to conquer the longed for trophy. In this article we’ll demonstrate this fact.

The data

We’ve borrowed the data for this study from the UEFA’s official page. If you go to this address http://www.uefa.com/uefachampionsleague/season=2011/matches/all/index.html# you’ll see all the matches played in the season 2010/2011. Change the year in the query string to see another year’s results. With this information we’ve created a very simple CSV file which summarises the competition from the round of 16. We’ve taken the resuls from the season 2004/2005 because is the first season with the actual format (the knockout rounds start at the round of 16). The CSV file looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
year,round,team1,team2,winner
2004,8,Lokomotiv Movska,Monaco,Monaco
2004,8,Celta,Arsenal,Arsenal
2004,8,Bayern,Real Madrid,Real Madrid
2004,8,Sparta Praha,Milan,Milan
2004,8,Stuttgart,Chelsea,Chelsea
2004,8,Porto,Man. United,Porto
2004,8,Real Sociedad,Lyon,Lyon
2004,8,Deportivo,Juventus,Deportivo
2004,4,Porto,Lyon,Porto
2004,4,Milan,Deportivo,Deportivo
2004,4,Real Madrid,Monaco,Monaco
2004,4,Arsenal,Chelsea,Chelsea
2004,2,Monaco,Chelsea,Monaco
2004,2,Porto,Deportivo,Porto
2004,1,Monaco,Porto,Porto

Loading the data

We have a CSV file, we’re going to use F#… CSV type provider to the rescue!!

We’re going to use Paket so add this lines to your paket.dependencies file

1
2
3
source https://nuget.org/api/v2

nuget FSharp.Data

And this line to the paket.dependencies file of your project:

1
FSharp.Data

Run the install command of paket and you’ll have FSharp.Data referenced in your project. To use it from your script file, we have to reference it:

1
#r "../packages/FSharp.Data/lib/net40/FSharp.Data.dll"

and open it:

1
open FSharp.Data

Now we’re ready to load the data. To keep things simple we’re going to use just a couple of types to store the data

1
2
type Team = string
type RoundGame = {Year: int; Round: int; Team1:Team; Team2:Team; Winner:Team}

Let’s use the fantastic CSV type provider to load all the games:

1
2
3
4
5
6
type ChampionsLeague = CsvProvider<"year,phase,team1,team2,winner", Schema = "year(int),phase(int),team1,team2,winner">

let file = __SOURCE_DIRECTORY__ + "\Data\champions.csv";
let text = File.ReadAllText(file)

let championsLeagues = ChampionsLeague.Load(file);

And finally, let’s parse the data into the recently defined types:

1
2
3
let champions =
    championsLeagues.Rows
    |> Seq.map(fun r -> {Year = r.Year; Round = r.Phase; Team1 = r.Team1; Team2 = r.Team2; Winner = r.Winner})

Glories from the past

First of all let’s review how many times a Premier League team has won the Champions League in the last twelve years. Premier League teams are very powerfull and they play a great football, I’m sure we’ll find a lot.

1
2
3
4
5
let championsWonBy teams =
    champions
    |> Seq.filter(fun f -> f.Round = 1 && teams |> Array.contains f.Winner)

championsWonBy [|"Liverpool"; "Man. United"; "Chelsea"; "Man. City"; "Arsenal"|] 

Not too bad. Liverpool in 2005, Manchester United in 2008 and Chelsea in 2012 won the Champions League. So, every 3.5 years a Premier League team wins the Champions League. Maybe 2016 will be the next time?

Let’s compare that with other leagues, I’m sure Premier League will be the strongest one!

Germany and Portugal have won 1 cup, Italy 2 and Spain 5. That puts Premier League in second position, not bad!

As I’m F.C. Barcelona fan, let me see how many Champions League we won in the past twelve years… 4. One more than the whole Premier League… Well, we have Messi. It’s like cheating a bit… ;)

Round of 16

In the round of 16 there were two teams representing Premier League: Arsenal and Manchester City. Arsenal played against Barcelona and they lost. Let’s study their last matches to see if that was an unexpected result:

1
2
3
4
5
let roundWith team1 team2 =
    champions
    |> Seq.filter(fun f-> (f.Team1 = team1 && f.Team2 = team2) || (f.Team1 = team2 && f.Team2 = team1))

roundWith "Arsenal" "Barcelona"

That gives us three results: Final of 2006, quarter-finals of 2010 and round of 16 of 2011. In all theses matches Barcelona won, so it wasn’t a great surprise that this year they’ve won too…

Let’s study Manchester City a bit. We can start analysing how many times they’ve played a quarter-final match.

1
2
3
4
5
6
let timesInPhase phase team =
    champions
    |> Seq.filter(fun g -> (g.Team1 = team || g.Team2 = team ) && g.Round = phase)
    |> Seq.length
    
"Man. City" |> timesInPhase 4

Wow, they never played a quarter-final game! Let’s study then their games in round of 16. They are a very rich and powerful team, so I guess they have played a lot of games in that round.

1
"Man. City" |> timesInPhase 8

Mmmmm… only two. Let’s take a look at those games

1
2
3
4
5
let gamesInRound round team =
    champions
    |> Seq.filter(fun g -> (g.Team1 = team || g.Team2 = team ) && g.Round = round)

"Man. City" |> gamesInRound 8

They played both times against Barcelona and they lost… So, Barcelona is definetively a rival to avoid in the next round.

Manchester City plays against Paris St Germain. Have they played any game before?

1
roundWith "Man. City" "Paris"

No, they’ve never played before. Let’s take a look at PSG games in quarter finals:

1
"Paris" |> gamesInRound 4

PSG has played three times in quarter finals. Two against Barcelona (2013 and 2015) and one against Chelsea (2014). They have lost the three of them, so it could be a good team to play against.

Semifinals

Let’s imagine Manchester City wins PSG at quarter-final round. Which team could be the best rival to play against? Let’s see if anyone of those teams have never played a semi-final round.

1
2
3
4
let rivals = ["Barcelona"; "Real Madrid"; "Atletico"; "Wolfsburg"; "Bayern"; "Benfica"]

rivals
|> Seq.filter(fun f -> timesInPhase 2 f = 0)

Wolfsburg and Benfica have never played a semi-final. Actually, only they have never played a final (remember, in the last twelve years). And yes, this is the first time they are playing a quarter final. So let’s study a bit their rivals to see which of them have more chances to win.

Wolfsburg plays agains Real Madrid. Let’s see how Real Madrid played the quarter final round:

1
2
"Real Madrid" |> gamesInRound 4 |> Seq.length
"Real Madrid" |> gamesInRound 4 |> Seq.filter(fun f-> f.Winner <> "Real Madrid") |> Seq.length

They played six times and they won five. They don’t seem a good team to play against.

Lets take a look at Bayern, Benfica’s rival. They’ve played eight times the quarter final round, and they’ve been eliminated three times. In 2005 they lost against Chelsea (finalist). In 2007 they lost against Milan (semi-finalist) and in 2009 they lost against Barcelona (winner). So, although they’ve lost against great teams, it looks like Benfica has more chances to win them than Wolfsburg to win Real Madrid.

In case nor Benfica neither Wolfsburg can win their games, who will be a good rival? Well, we can say that the best rival is the one that has less percentage of winnings in semi-finals. Let’s calculate it.

1
2
3
4
5
6
7
8
9
let winsInRound round team =
    let games = team |> gamesInRound round
    float (games 
            |> Seq.filter(fun f -> f.Winner = team)
            |> Seq.length ) / float (games |> Seq.length)

rivals
|> Seq.map(fun f -> f, f |> winsInRound 2)
|> Seq.sortBy snd 

Looks like Real Madrid is the worst team playing semi-finals. So, if Benfica or Wolfsburg can’t pass to semi-final, maybe Real Madrid could be a good rival.

Final

Let’s get the teams with worst percentage of victories in a Champions League final.

1
2
3
rivals
|> Seq.map(fun f -> f, f |> winsInRound 1)
|> Seq.sortBy snd

Well, Barcelona is not a very good rival… They’ve played four finals and they’ve won all of them. Something similar applies to Real Madrid, but just for one final. Bayern only wins one of every three finals they play. And Atletico only has played one final and they’ve lost it. So, if Manchester City gets to the final, Atletico could be a good rival.

Recap

Well, taking a look at the last twelve years results it’s quite clear that no Premier League team will win this Champions League edition. But there’s a little chance to win if they play well and have luck in the next draw. Only one thing seems clear: don’t play against Barcelona!! :-)