Make your pizzas taste better thanks to the F# Forward Pipe operator!

In today’s post we will take a closer look at the F# forward pipe operator represented by the following |> symbol. We already saw this operator in action in my two previous posts about Polish surnames that you can find here and here. In this session we will go over:

  • The definition and basic usage of the |> operator
  • An advanced example written in both C# and F#, illustrating the expressive power of |>

Back to Basics

If we search for the definition of the operator in the source code, we can find this:

/// Apply a function to a value, the value being on the left, the function on the right
/// arg: The argument.
/// func: The function.
val inline ( |> ) : arg:'T1 -> func:('T1 -> 'U) -> 'U

The function signature can be a bit scary if you’re not familiar with F#, but in reality it is pretty straightforward. Let’s look at an example:

let add a b = a + b
let res1 = add 2 3 // res1 = 5

We just defined a new add function that takes 2 operators a and b and sums them. Then we execute this function once and store the result in res1, 5 in this case. But what if we used the |> operator to achieve the same effect:

let res2 = 3 |> add 2 // res2 = 5

Or, with a bit of extra formatting:

let res3 =
    3
    |> add 2

What happens is that we simply take the value on the left of the operator, and we pass it (or pipe it) as the last parameter of the function on the right of the operator. And that’s all we need to know. Nothing more, nothing less.

Right now you’re probably thinking “But why, Roberto? Why!?”. That’s a very pertinent question. My answer is — and I feel this deserves the HTML <blockquote> treatment —

because it allows you to chain an arbitrary amount of function calls while keeping your code readable and elegant.

Here Be Pizzas

That was pretty simple. We need a more advanced example to illustrate the true power of the forward pipe operator: Pizzas


Let’s have a look at the following C# service that makes and delivers pizzas (I voluntarily left out the implementation details so we can focus on the topic at hand). The full code is available on this public gist.

public class PizzaRecipe {}
public class PizzaOrder {}
public class ColdPizza {}
public class HotPizza {}
public class PizzaDelivery {}

public static class PizzaService
{
    public static PizzaOrder OrderPizza(PizzaRecipe recipe, string size)
    {
        return new PizzaOrder();
    }
    
    public static ColdPizza PreparePizza(PizzaOrder order)
    {
        return new ColdPizza();
    }
    
    public static HotPizza CookPizza(ColdPizza pizza, int temperature)
    {
        return new HotPizza();
    }
    
    public static PizzaDelivery DeliverPizza(HotPizza pizza)
    {
        return new PizzaDelivery();
    }
}

Now, if we wanted to use this API and implement the full pizza delivery process, we’d certainly have a few design options. The first one would be:

// The ol' good way.
public PizzaDelivery BigPizzaProcess(PizzaRecipe recipe)
{	
    var order = OrderPizza(recipe, "big");
    var coldPizza = PreparePizza(order);
    var hotPizza = CookPizza(coldPizza, 180);
    var delivery = DeliverPizza(hotPizza);
	
    return delivery;
}

This is pretty standard, quite a lot of local variables but that does the job. There’s also this option:

// The Arabic way: you read from right to left!
public PizzaDelivery BigPizzaProcess(PizzaRecipe recipe)
{	
    return DeliverPizza(CookPizza(PreparePizza(OrderPizza(recipe, "big")), 180));
}

Although I might scream a bit if I saw something like this on production! As you can see, you’d have to read it from the right to the left to get the proper order of execution.Not very convenient. Also, adding new steps to the process would quickly turn the whole thing into a mess.

Finally, you might want to write a few extension methods:

public static class PizzaExtensions
{
    public static PizzaOrder Order(this PizzaRecipe recipe, string size)
    {
        return PizzaService.OrderPizza(recipe, size);
    }
	
    public static ColdPizza Prepare(this PizzaOrder order)
    {
        return PizzaService.PreparePizza(order);
    }
	
    public static HotPizza Cook(this ColdPizza pizza, int temperature)
    {
        return PizzaService.CookPizza(pizza, temperature);
    }
	
    public static PizzaDelivery Deliver(this HotPizza pizza)
    {
        return PizzaService.DeliverPizza(pizza);
    }
}

And end up with something like this:

// The nice way!
public static PizzaDelivery BigPizzaProcess(PizzaRecipe recipe)
{
    return recipe
        .Order("big")
        .Prepare()
        .Cook(180)
        .Deliver();
}

Now we’re talking! The code is clean and it almost reads like natural English. Even someone with little or no knowledge in programming would be able to quickly guess what the code is doing. I actually conducted the experiment with my girlfriend and she understood and explained the code in less that 30 seconds. Please try this at home and let me know of the results in the comments section!

It took some extra effort to get there though. The extensions methods that we created will need to be maintained and tested too. Nothing too complex so far, but it needs to be done anyway. Let’s have a look at the F# equivalent now:

open System

type PizzaRecipe() = class end
type PizzaOrder() = class end
type ColdPizza() = class end
type HotPizza() = class end
type PizzaDelivery() = class end

let order (size:string) (recipe:PizzaRecipe) =
    PizzaOrder()

let prepare (order:PizzaOrder) =
    ColdPizza()

let cook (temperature:int) (pizza:ColdPizza) =
    HotPizza()

let deliver (pizza:HotPizza) =
    PizzaDelivery()

let bigPizzaProcess (pizzaRecipe:PizzaRecipe) =
    pizzaRecipe
    |> order "big"
    |> prepare
    |> cook 180
    |> deliver

That’s it, really! Thanks to the Pipe operator in F#, we achieved the same nice and readable code as the C# version, but without the hassle of setting up all the additional extension methods. One could argue that the F# version falls even closer to natural English, due to the absence of the all the parentheses, brackets, dots and semicolons that are present in the C# sample.

As a result, the F# code is much more compact with only 26 lines of code versus 65 lines for the C# version. That’s 40% less code to test and maintain! What we have here is only a small example, but I let you imagine what would that mean for a large-scale application.

That’s all for today. As always, don’t hesitate to leave your comments or questions at the bottom of the page.

Cheers!

Are you Polish? F# will tell us (probably)! Part 2/2

In yesterday’s post we had our first glance at F# and how we would use it to answer the question that is on everyone’s lips: is your surname Polish? In today’s post (the 2nd and last one of this series) we will go over the rest of the script that you can find on this public gist.

We already went over the countCharCI function that returns the number of occurrences of a given character in a word. We can simply call the function like this:

countCharCI 'C' "ccc" // returns

What we’d like to do now is implement the concept of points, and more particularly this:
Each Polish letter will earn the surname 1 point. For instance, If a word contains 3 polish letters, we’d like to assign 3 points to it.

Handling Polish letters

I introduced the new computePointsFor function to help us achieve this:

/// Apply a function to all elements of a list, sum the results and multiply by the number of points
let computePointsFor func elems points word =
    elems
    |> List.map (fun e -> func e word)
    |> List.reduce (+)
    |> (*) points

The function returns an int and takes 4 parameters as input:

  • func is a function that takes two parameters of type ‘a and ‘b and returns an int
  • elems is a list of ‘a
  • points is an int
  • word is of type ‘b

You may wonder what are those ‘a and ‘b about. This is the F# way of representing generic types! In C#, We’d probably have T1 and T2 instead. As explained in the previous post, F# is able to infer all those types from their usage.

The second interesting thing here is, as I mentioned above, func is a function! As F# is a functional-first programming language, functions are treated as first-class citizens and you can pass them around as you normally would for any other parameter. This is of course possible in C# too, but it doesn’t feel as natural and simple as in F#, especially when you throw generic types in the mix.

What does computePointsFor actually do? we already are familiar with the |> operator that we previously saw in the countCharCI function. We can see at a glance that the function is composed of 3 steps:

  1. It applies the func function on every element of the elems list, using List.map. It also uses word as the second parameter of func. This steps returns a list of ‘c.
  2. It then sums together all elements from the previous steps, using the addition operator (+) in combination with List.reduce. List.reduce iterates over a list of elements, applying a function on them and storing the results in an accumulator that is passed to the next iteration, until it reaches the end of the list. This step returns an int.
  3. The last step takes the int returned from step 2 and multiplies it by the points parameter. The end result is of course an int.

Now that we have the function implemented, let’s test it:

let polishChars = ['ą';'ć';'ę';'ł';'ń';'ó';'ś';'ż';'ź']

computePointsFor countCharCI polishChars 1 "Bob Johnson" // returns 0
computePointsFor countCharCI polishChars 1 "Robert Jonsłon" // returns 1
computePointsFor countCharCI polishChars 2 "Stanisław Wójcik" // returns 4
computePointsFor countCharCI polishChars 1 "" // returns 0

It seems to work as expected! Cool. As you can see, I passed countCharCI as the func parameter, the list of Polish characters polishChars as the elems parameter, 1 as the number of points, and  the surname we want to test against as the last parameter.

So far so good, but what if we were a bit more demanding and tried to make our code more readable? Let’s create the new checkPolishChars functions that wraps nicely around countCharCI and polishChars to make our calls clear and succinct:

// Helper function with pre-baked parameters
let checkPolishChars points word =
    computePointsFor countCharCI polishChars points word

And let’s test it:

checkPolishChars 3 "Józef Gwóźdź" // returns 12

Perfect. It looks like we are done with handling Polish letters, so let’s go over the digraphs next.

Handling Polish digraphs

Similar to the countCharCI function we saw above, I created countDigraphCI as shown here:

/// Return the number of occurrences of a given digraph within a word (case-insensitive)
/// The function ignores overlaps (countDigraphCI "cc" "cccc" returns 2 and not 3)
let countDigraphCI (digraph:string) (word:string) =
    let wordCI = word.ToLower()
    let digraphCI = digraph.ToLower()

    let rec loop occurrences index =
        if index >= String.length wordCI then occurrences
        else
            match wordCI.IndexOf(digraphCI, index) with
            | -1 -> occurrences // -1 means the substring was not found
            | indexFound -> loop (occurrences + 1) (indexFound + String.length digraphCI)
    
    if String.length word = 0 then 0
    else loop 0 0

It obviously takes 2 parameters as input, a digraph and a word, both of type string. There is something very interesting in this function, something that we haven’t seen yet in the previous examples. It seems like there is… a function within the function?! That’s correct, the loop function is actually defined inside countDigraphCI. Note that this functionality was recently added to C# 7.0, under the name of local functions.

The logic of loop is straightforward. It is decorated by the rec keyword, which means that the function is recursive. It looks for the first occurrence of the given digraph within word, by using the String.IndexOf function from the .NET framework. If the digraph was found, it increments the occurrences counter and recursively calls itself once again, this time starting at the new index. It continues to do so until it reaches the end of the string.

“But Bryan, why not use a good ol’ for loop instead? Why confuse us with this whole recursive wabble babble?, you ask. This is because using a standard for loop would require creating a mutable variable to store the current state (the occurrences parameter here). And F#, being a functional-first language, doesn’t really like having states and mutable stuff. Let’s see the new function in action:

countDigraphCI "cz" "Szczerba" // 1
countDigraphCI "cz" "szCZerba" // 1
countDigraphCI "sz" "Szczerba" // 1
countDigraphCI "sz" "" // 0
countDigraphCI "cz" "Wieczorkiewicz" // 2

It seems to be working fine, once again. Let’ reuse our computePointsFor function and apply it here too:

// A digraph is a combination of letters that represent a single sound!
let polishDigraphs = ["ch";"cz";"dz";"dż";"dź";"rz";"sz"]

/// Apply computePointsFor to our countDigraphCI function
let checkPolishDigraphs points word =
    computePointsFor countDigraphCI polishDigraphs points word

checkPolishDigraphs 1 "szczrz" // 3
checkPolishDigraphs 2 "Dziurdź" // 4
checkPolishDigraphs 3 "Szczerba" // 6
checkPolishDigraphs 1 "Błaszczyszyn" // 3

Boom! I hope you can see how convenient it is to be able to pass two different functions with different signatures to computePointsFor and let F# deal with all the types automatically.

Time to take care of our last problem, the Polish endings.

Handling Polish endings

The finishWithCI function is straightforward and makes use of the String.EndsWith function that is part of the .NET framework. Here is its implementation together with a series of tests:

/// Check whether a word has the given ending (case-insensitive)
let finishWithCI (suffix:string) (word:string) = word.ToLower().EndsWith(suffix.ToLower())

finishWithCI "ski" "kowalski" // true
finishWithCI "SKi" "kowalsKI" // true
finishWithCI "wicz" "Nowak" // false
finishWithCI "" "Nowak" // true
finishWithCI "" "" // true
finishWithCI "ski" "" // false

However, checking if a given surname has one of the possible endings we defined earlier is a bit different than counting the number of occurrences of a letter or a digraph. So I needed another function, checkConditions, defined below:

/// Apply a list of criteria on a subject and return as soon as one matches the given condition
let checkConditions criteria condition subject =
    let rec loop remainingElems = // sub-function, loop over the criteria
        match remainingElems with
        | [] -> (false, None)
        | c::r -> 
            match condition c subject with
            | true -> (true, Some c) // exit as soon as we get a positive result
            | false -> loop r // else loop over the next element
loop criteria

I won’t go into too much details here because this post is getting long enough, but we can notice two things:

  1. checkConditions also defines a local recursive function called loop.
  2. The loop function makes extensive use of an F# feature called pattern matching. I will most probably write a separate post on this topic as this is a very powerful mechanism.

The function basically checks a condition against a list of criteria and returns as soon as one of the criteria fulfills the condition. It returns a tuple of the following form:

  • either (false, None) if no criterion fulfilled the condition.
  • or (true, Some criterion) if a criterion fulfilled the condition.

We can see it in action below:

checkConditions polishEndings finishWithCI "Kowalski" // returns (true, Some "ski")

And conclude the part about the Polish endings, let’s wrap those functions in a convenient and clear helper:

/// Return a certain amount of points if the given word has one of the most common Polish endings
let checkPolishEndings points word =
    let success, _ = checkConditions polishEndings finishWithCI word
if success then points else 0

We’re almost there!

We are very close to getting our magical function that tells us if a surname is Polish or not. I created a new type that would represent our possible answers. This is called a discriminated union in F#:

type NameOrigin = DefinitelyPolish | ProbablyPolish | NotPolish

Let’s throw 2 more functions in the mix. The first one is calculatePolishDensity and the comment below is self-explanatory. It also makes use of pattern matching:

/// Divide the number of points obtained for a given word by the length of the word itself
let calculatePolishDensity (word:string, points) =
    match word.Length with
        | 0 -> (word, 0.)
        | len -> (word, float points / float len)

The second one is decideIfPolish and converts the Polish density parameter to NameOrigin based on the rules we defined in our previous post:

  • Any density below 0.2 would yield Not Polish.
  • Any density between 0.2 and 0.8 would yield Probably Polish.
  • Any density above 0.8 would yield Definitely Polish.

Once again, the implementation is straightforward:

/// Decide if a word is Polish based on its density
let decideIfPolish (word, density) =
    if (density < 0.2) then (word, NameOrigin.NotPolish, density)
    else if (density >= 0.2 && density <= 0.8) then (word, NameOrigin.ProbablyPolish, density)
    else (word, NameOrigin.DefinitelyPolish, density)

Let’s prepare the terrain for our final function and create checkAllPolishConditions that will calculate the total number of points for a surname, based on Polish letters, digraphs and endings:

let checkAllPolishConditions pointsPerChar pointsPerEnding pointsPerDigraph = 
    checkPolishCharsPipe pointsPerChar
    >> checkPolishEndingsPipe pointsPerEnding
    >> checkPolishDigraphsPipe pointsPerDigraph

The >> operator is called the composition operator in F#. It allows to create one big function out of several smaller functions with compatible signatures. We will surely go back to this topic in a future post.

And here it finally comes, the long-awaited isNamePolish function in all its splendor:

let isNamePolish name =
    (name, 0)
    |> checkAllPolishConditions 1 6 3
    |> calculatePolishDensity
    |> decideIfPolish

which checks all conditions and assigns points, calculate the Polish density and then decides whether the name is Polish based on the score obtained! Unleash the beast!

isNamePolish "Młynarczyk" // returns ("Młynarczyk", DefinitelyPolish, 1.0)

Młynarczyk is Definitely Polish, the algorithm got it right. Next!

isNamePolish "Johnson" // returns ("Johnson", NotPolish, 0.0)

Johnson is Not Polish, once again the algorithm worked as expected! Let’s try one more.

isNamePolish "Kowalski" // ("Kowalski", ProbablyPolish, 0.75)

Hmm, the algorithm says Probably Polish whereas the expected result would be Definitely Polish. We’d probably need to tweak it a bit, either by updating the points system or the decision based on the density.

Last one for the road, as requested by my colleague Marcin. Brzęczyszczykiewicz. This has got to be the most Polish, or polishest if you will, surname ever. and the result is…

isNamePolish "Brzęczyszczykiewicz" // returns ("Brzęczyszczykiewicz", DefinitelyPolish, 1.157894737)

Definitely Polish!

Thank you F#, you are amazing!

This concludes our series about Polish surnames, hope you liked it! Don’t hesitate to leave your remarks or questions in the comments, I’ll be glad to address them.

Cheers!

Are you Polish? F# will tell us (probably)!

      3 Comments on Are you Polish? F# will tell us (probably)!

In my previous post I created a small Hello, World! web application using WebSharper. As F# is predominant in WebSharper, I figured I’d write a few posts about the language itself. I didn’t want to write yet another F# tutorial focused on theory (there are plenty of those out in the Wild), so I came up with a simple use case I could use as material for those posts. How about we wrote a small script that would tell the probability a given surname is Polish?


This would serve as:

  • a smooth and practical introduction to F# for those who don’t know it yet, with just a pinch of functional programming theory (nothing too complicated, I promise).
  • a short refresher for the others (myself included),
  • a unique opportunity to learn a little more about Polish surnames!

Let’s start then. First, let’s describe the problem a hand and what we want to achieve. Given an arbitrary surname, we want to know if it is either:

  • Definitely Polish
  • Probably Polish
  • Not Polish

The magical algorithm

In order to do so, I came up with a rather naive algorithm that would help us get the desired results. This algorithm is based on 3 rules:

  • How many exclusive Polish letters does the surname contain?
    The Polish language has a set of of 9 letters based on the Latin alphabet, but combined with diacritics. Here is the complete list: ą, ć, ę, ł, ń, ó,’ś, ż, ź
  • How many Polish digraphs does the surname contain?
    Put simply, a digraph is a pair of letters that, combined together, form a new letter with a sound on its own. The Polish language contains 7 digraphs: ch, cz, dz, dż, dź, rz, sz
  • Does the surname end with a common Polish ending?
    After analyzing a few dozens of popular Polish surnames, I put together a list of the most common endings: wicz, czyk, wski, wska, ński, ńska, ski, ska, cki, cka, ło, ła, ak, rz
    You will notice that some of them are quite similar, like wski / wska or cki / cka. The forms ending by i usually mean the bearer is a man while the ones ending by a mean the bearer is a woman. Easy!

The algorithm would be a bit too minimalist if we stopped here, so I decided to introduce the concept of points to it:

  • Each Polish letter will earn the surname 1 point.
  • Each Polish digraph will earn the surname 3 points.
  • A Polish ending will earn the surname 6 points!

And last but not least, by dividing the total of points by the number of letter in the surname, we would obtain its Polish density, which in turn would give us our final answer:

  • Any density below 0.2 would yield Not Polish.
  • Any density between 0.2 and 0.8 would yield Probably Polish.
  • Any density above 0.8 would yield Definitely Polish.

Let’s apply this to a sample surname: Młynarz

  • it would earn 10 points (1 for the ł letter, 3 for the he rz digraph, and 6 for the rz ending!)
  • the density would be 10 points divided by 7 letters = 1.43
  • the expected end result would be: Definitely Polish

Voilà! As you’re probably blown away by the complexity of the algorithm, let’s catch our breath and have a little .gif instant (I included a version with Polish subtitles, of course).

The magical code

Without further ceremony, let’s go over the code that you can find on this public gist (or alternatively on the GitHub repo). Here are a few figures about it. The single file contains:

  • 167 lines in total
    • of which 60 are either blank lines or comments (35.9%).
    • of which 39 are evaluations or tests (23.4%).
    • of which 68 are actual logic (40.7%).
  • 3 declarations containing the Polish letters, digraphs and endings described above.
  • The whooping total of 16 function definitions! That’s an average of 4 lines per function.

The file is an F# script (with the .fsx extension), which means you can run it dynamically within the F# Interactive console, by highlighting part of the code, right-clicking and choosing the Execute in Interactive option within Visual Studio:

(click on the GIF to enlarge)This is a wonderful feature that allows for very fast development cycles: you write a new function, test it as you go and copy it over to your production code once you are pleased with the results.

Let’s have a look at the very first function of the script, countCharCI. The function returns the number of occurrences of a character within a given word, and it obviously takes 2 parameters as input: char and word.

/// Return the number of occurrences of a given char within a word (case-insensitive)
let countCharCI char word =
    word
    |> Seq.filter (fun current -> Char.ToLower current = Char.ToLower char) 
    |> Seq.length

Do you even strongly-type, bro?

I hear you say already “But Jimmy, isn’t F# supposed to be a strongly-typed language? Can’t see any of those type declarations in here.”. Thanks for asking. This is because the F# compiler features a powerful type inference system and is able to guess the type of your parameters from their usage (most of the time).

Even if you don’t directly see them in the code, the types are really there though and will be enforced by the compiler and run-time. This prevents a lot of funky issues you could get with weakly-typed languages (Yes JavaScript, I am looking at you!). You can check this by hovering over the parameters’ names in Visual Studio.

The char parameter is of type char:

The word parameter is of type seq<char> (a sequence of char, which a string is):

And finally the whole function has the following signature: char:char -> word:seq<char> -> int

Which basically means that it takes 2 parameters as input (the char and the seq<char>) and returns an int. Perfect!

Sometimes though, the F# compiler will need our help figuring out the type of certain parameters. This is for instance the case for our one-liner finishWithCI function at line 92:

/// Check whether a word has the given ending (case-insensitive)
let finishWithCI (suffix:string) (word:string) = word.ToLower().EndsWith(suffix.ToLower())

Here we need to explicitly state the type of both suffix and word parameters in order to use the ToLower and EndsWith functions on them. This lets the compiler know that those 2 functions indeed belong to the String type. There are currently 32 parameters defined in the whole script, but only 5 of them actually are explicitly annotated. I love it!

As this post is getting pretty long (once again!), let’s end by going over the logic of countCharCI:

/// Return the number of occurrences of a given char within a word (case-insensitive)
let countCharCI char word =
    word
    |> Seq.filter (fun current -> Char.ToLower current = Char.ToLower char) 
    |> Seq.length

The function makes use of the Forward Pipe operator |> twice. This operator is omnipresent in F# and we will dedicated a whole blog post to it soon. Simply put, what it does is pass the value on the left side (word here) as the last parameter of the function on the right side (Seq.filter).

The Seq.filter function applies its 1st parameter, a predicate function, to each element of the sequence passed as its 2nd parameter. In our particular case, it will check if characters contained in word match the reference character passed to countCharCI. It will make the comparison case-insensitive by calling Char.ToLower on each side of the equality operator first:

fun current -> Char.ToLower current = Char.ToLower char

The fun keyword above allows to define a lambda expression, the same way as you would in C#.
Please note that C# uses a fat arrow => while F# uses a slim arrow ->.
The Seq.filter itself returns a new sequence of characters that matched the predicate above. This sequence is then piped to Seq.length that simply returns its total length (thus the number of occurrences of char within word).

We’re almost there. Let’s test our shiny new function with the following evaluations:

countCharCI 'C' "ccc" // returns 3
countCharCI 'c' "cCc" // returns 3
countCharCI 'c' "" // returns 0
countCharCI '2' "145" // returns 0
countCharCI '3' "3f3sdf" // returns 2

It works! Let’s call it a day! I will follow up with a second post where we will see the whole script in action, and finally get to answer the crucial question: Is your surname Polish?

More soon, take care!

Hello, WebSharper!

      3 Comments on Hello, WebSharper!

In my previous post I was explaining why I chose WebSharper as my main topic for DSP 2017. If you haven’t read it yet, here’s the short answer: full-stack Web Dev, F#, and no JavaScript. So yesterday I put on my coding pants and got to work. More or less one hour later, I ended with a rather simple but functional website that looks like this:

(click on the GIF to enlarge)

As you can see, the website basically does just two things:
– it queries for your name, and then says ‘Hello!’ to you. This is done on the server side.
– it displays the number of times you click on the 2nd button. This is done on the client side.

All this in just about one hour? Not bad at all, especially for a noob like me! Let’s see in details what I did to get there. You can download the source code from my GitHub repo.

The initial setup

In order to use WebSharper, you need to install a couple of things first. Don’t worry, it won’t cost you a penny. Head down to their download page and click on the download link for your favourite editor. I’m personally using Visual Studio 2015 Community Edition that you can download for free from here.


Run the WebSharper.vsix file and follow the setup instructions. Once it is done, you should end up with a bunch of new templates in Visual Studio, under the following path:
Templates → Other Languages → Visual F#  → WebSharper


That’s a lot of different options and we will look at a few of them in coming posts. For now I decided to go with the Self-Hosted Client-Server Application, which basically represents a regular website with interactions between the server and the browser.With this option the web server consists of a single executable file (the Visual Studio project’s output is a console application).


As the description says, the website will be self-hosted using OWIN but WebSharper supports other hosting options like IIS and Suave. As I was lazy and didn’t want to do any extra configuration this seemed to me like the best choice.

Show us the code already!

You’re right, time to take a deeper look at the innards of the website. The project is rather small and consists of the following files:
of which only four will be of interest to us:

  • Main.fs
  • Main.html
  • Client.fs
  • Remoting.fs

Combined together they represent around 150 lines of code and HTML. That’s not a lot, and this includes comments, blank lines and open statements (the F# equivalent of using in C# or import in Java)!  It took me around 30 minutes to understand the relations and dependencies between each file, so let me guide you through the most interesting parts. You can browse the full files directly from the GitHub repo):

Main.fs

type EndPoint =
    | [<EndPoint "GET /">] Home

This type will list all endpoints (pages, URLs…) of your website. Here we just have one endpoint, which will be our Home page. It can be accessed via a HTTP GET call to the root URL of our website (http://localhost:9000/ in our case).

    [<Website>] // Main entry point for our application
    let Main =
        Application.MultiPage (fun context action ->
            match action with
            | Home -> HomePage context
        )

This snippet defines our routing rules. Here the configuration says that when a HTTP GET call to http://localhost:9000/ is received, the server should respond by calling a certain HomePage function. This function is defined below:

let HomePage context =
        Templating.Main context EndPoint.Home "Hello WebSharper" [
            H2 [Text "Welcome to Hello WebSharper. What's your name?"]
            Div [ClientSide <@ Client.Main() @>]
        ]

The function defines the structure of our main page. The title of the page will be ‘Hello WebSharper’ and the page itself will consist of two HTML elements:

  • A h2 header containing the text ‘Welcome to Hello WebSharper. What’s your name?’
  • A div container with the ‘weird’ syntax below
Div [ClientSide <@ Client.Main() @>]

This simply says that the code from the Main function of the Client Module should be inserted within this particular div element. Here is the code of the Main function in question:

Client.fs

[<JavaScript>]
module Client =

    let Main () =
        let input = Input [Attr.Value ""] -< []
        let output = H1 [Text "Hello, Stranger...?"]
        let inputValue = H4 []
        let someStaticText = P []
        let mutable clickCounter = 1

        Div [
            input

            Button [Text "Send to server"] // Sends a request to the server
            |>! OnClick (fun _ _ ->
                async {
                    inputValue.Text <- input.Value
                    let! data = Server.sayHelloAsync input.Value
                    output.Text <- data
                }
                |> Async.Start
            )

            Div [Attr.Class "hello"] -< [output]
            
            HR []
            
            Button [Text "Run some client-side action"] // Runs an action on the client side
                |>! OnClick (fun _ _ ->
                    someStaticText.Text <- sprintf "You clicked the button %d times." clickCounter
                    clickCounter <- clickCounter + 1
                )

            Div [] -< [someStaticText]
        ]

There are two things to note here:

  1. The [<JavaScript>] attribute is part of WebSharper and explicitly tells the compiler that the whole logic of the Client module should be transpiled to JavaScript.
  2. The Main function just defines a bunch of other HTML elements. The most worthy of attention are the two buttons with their associated logic expressed via the OnClick functions.

The first button called ‘Send to server’ is actually making an asynchronous HTTP POST call to the server upon click.

async {
    //...
    let! data = Server.sayHelloAsync input.Value
    //...
}

The sayHelloAsync function is defined in our Remoting.fs file:

Remoting.fs

module Server =
    
    let sayHello usr = "Hello, " + usr + "!"

    [<Remote>]
    let sayHelloAsync username =
        async { return sayHello username }

Note the use of the [<Remote>] attribute from WebSharper. It enables to call a function defined on the server-side directly from the client-side! Now, since the client-side code is transpiled from F# to JavaScript, let’s have a look at what happens under the hood when such function is called:

  1. The data passed to Server.sayHelloAsync is serialized to Json on the client-side (JavaScript).
  2. It makes an asynchronous call (HTTP POST) to the Server.sayHelloAsync on the server-side (JavaScript).
  3. The server deserializes the Json data and processes it (F#).
  4. The server serializes the answer to Json and sends it back to the client (F#).
  5. The client receives the data and processes it (JavaScript).

Now, I don’t know about you, but this seems pretty powerful to me! How much time do programmers normally waste on getting all those steps right? How many times did you have issues with Json serialization or deserialization, or simply getting the URL right? Not to mention contracts changing on either side of the wire. You can forget about all those problems here, as WebSharper takes care of it all for you. And this is the way it should be. I made another short GIF to illustrate what we’ve just described:

(click on the GIF to enlarge)

This post is getting pretty long already, let’s wrap up. We haven’t talked about the role of the Main.html file and HTML bindings in WebSharper just yet. so this will probably be featured in a future post. You will also notice I created another project called HelloWebSharper.Tests. We will surely be going over this subject as well.

I hope you guys liked this introduction! Don’t hesitate to leave a comment if you have any questions or comments.

Cheers!

DSP 2017, here we come!

      4 Comments on DSP 2017, here we come!

Well hello!

This is my very first post dedicated to DSP 2017. Wait, what? You don’t know what DSP is? Take a moment to read this first, then. Don’t know me either? About time we got acquainted! All set? Let’s go on then. I know this is quite a long introductory post and I’ll try to keep the next ones shorter.

Incidentally this is also my very first post on a public blog. I’ve been wanting to try my hand at blogging for quite some time now, so I figured this would be the perfect opportunity to do so. After spending long hours looking for hosting options and domain prices, configuring WordPress, and most importantly, finding a decent-looking theme, here I finally am. Quite the adventure already!

In Quest of The Unimaginable

But having a blog is not enough to take part in DSP, for you also need a project! And this where things got a little complicated. There are literally so many things I’ve wanted to experiment with in the last few months that I couldn’t make up my mind. Would I go with a new language? A shiny framework? A cutting-edge tech? Ideas kept bouncing around in my head, but after some time, I realized all revolved around a certain pattern:

  • I’d surely like to try my hands at Web Dev
  • But… I don’t really like front-end work
  • But… I’ll need some kind of UI anyway
  • Shoo Shoo, JavaScript!
  • Damn, this F# looks pretty sexy!

At the first glance, some points seem pretty contradictory already! Let me expand on some of the ideas above.

…Why Web Dev?

Since the beginning of my career, I’ve been mostly working on server and desktop applications for enterprise. This is all fine and fun (well, not always), but there is this new thing in town called the Internet, and it seems to be catching up pretty fast. Who knows, companies might as well decide to use it too, at some point! So why not jump on the bandwagon?

…Why not front-end… but front-end after all?

I am what people from the IT sphere call a full-stack developer. I’ll spare you the technicalities, but that basically means I am able to implement both the business logic on the server (aka the back-end) and the UI logic on the client side (aka the front-end). However, I quickly started to notice one thing: those two worlds generally don’t cohabit well, and while I find it rather easy to keep the server side clean and tidy, working on the client side often feels like I am piling hacks over hacks (and oh god, I don’t like this). I truly believe the front-end is a domain on its own, and it should be reserved to dedicated and trained professionals. Let’s call them front-end developers. Catchy.

But since a GUI is generally accepted as the best way for users to mess with interact with your application, I guess I’ll have to live with it and compromise.

…Why not JavaScript?

The picture says it all. I tried, but I guess I’m not ready yet. Over the years, I’ve attended a few JavaScript trainings, went through the occasional Angular tutorials and whatnot, participated in React workshops, but it never caught on me. Maybe because I never understood why such a flawed language could get such a wide adoption. Anyhow, I promise I’ll give it another try, someday. Until then…

…Hello F#!

I was introduced to F# a few years ago by my good friend Krzysiek. Back then, I remained oblivious to its charms. Maybe I was too young. But after sinking a couple hundreds hours solving the same basic bugs, seeing resources and money being repeatedly wasted on common mistakes, studying patterns over patterns in the secret hope they would solve all our problems, or learning about performance issues the hard way, I started to seriously question the way we create software. Were we using the wrong tools? Was the blame to be put on us poor programmers? All those questions remained unanswered for quite some time.

But a couple of years later, I stumbled upon an article listing some of the basic features of F#. And It suddenly became all clear. Oh the immutability! Oh the purity! And the non-nullability… Did I mention composition? And pattern matching? Don’t worry. we’ll talk about all those in a future post.

Now, I am no F# developer. I don’t have any professional experience in using F#. The good news is, I don’t intend to leave it that way. Let’s see if F# lives up to its reputation (and If I’m worthy of it).

The Unimaginable Is Here?

I’m talking and talking, and all you’re probably thinking of is: Tell us about the project!
So to sum up, I am looking to do Web Dev with a limited amount of front-end knowledge, as little JavaScript as possible (ideally none), and with F# as the main language… Mission impossible? Fortunately there seems to be something just for me, and it is… WebSharper!

To put it simply, WebSharper is an open-source framework for Web Dev using F# for writing both the back-end… and the front-end! Awesome! Fear not, we’ll get into the details later. Until then, you can have a look at their official website here.

Let’s wrap up by listing what will be my goals and challenges for the next three months:

  • Blog, try out new ideas, and strive to keep you interested!
  • Get to learn WebSharper
  • Try my hand at Web Dev
  • Prove to myself and others than F# is an awesome language!

I want this DSP adventure to be all about the journey, not the destination, and as such I made the intentional choice not to commit to a specific task to implement just yet. Let’s see where the wind takes us.

Godspeed!