I've been teaching F# for over seven years now, both in the public F# FastTrack course that we runat SkillsMatter in London and in various custom trainings for private companies. Every time I teachthe F# FastTrack course, I modify the material in one way or another. I wrote about some of thisinteresting historylast year in an fsharpWorks article. The course now has a stable half-dayintroduction to the language and a stable focus on the ideas behind functional-first programming,but there are always new examples and applications that illustrate this style of programming.
When we started, we mostly focused on teaching functional programming concepts that might be usefuleven if you use C# and on building analytical components that your could integrate into a larger.NET solution. Since then, the F# community has matured, established theF# Software Foundation,but also built a number of mature end-to-end ecosystems that you can rely on such asFable,the F# to JavaScript compiler, andSAFE Stack for full-stack web development.
For the upcoming December course in London, I added a number of demos and hands-on tasks builtusing Fable, partly because running F# in a browser is an easy way to illustrate many conceptsand partly because Fable has some amazing functional-first libraries.
If you are interested in learning F# and attending our course, the nextF# FastTracktakes place on6-7 December in London at SkillsMatter. We also offer customon-site trainings. Get in touch at@tomaspetricekor emailtomas@tomasp.net for a 10% discount for the course.
One of the new samples I want to show, which I alsolive coded at NDC 2018,is building a simple web-based Excel-like spreadsheet application. The spreadsheet demonstratesall the great F# features such as domain modeling with types, the power of compositionalityand also how functional-first approach can be amazingly powerful for building user interfaces.
The sample compiles to JavaScript, so the best way of explaining what we want to build isto give you a live demo you can play with! Since this is a blog post about functional programming,I already implemented both Fibonacci numbers (column B) and factorial (column D) in the spreadsheet for you!
You can click on any cell to edit the cells. To confirm your edit, just click on any other cell.You can enter numbers such as1
(in cell B1) or formulas such as=B1+B2
in cell B3. Formulassupport parentheses and four standard numerical operators. When you make an edit, the spreadsheetautomatically updates. If you make a syntax error, reference empty cell or create a recursivereference, the spreadsheet will show#ERR
.
Full source code is available in myelmish-spreadsheet repository on GitHub(as a hands-on exercise in
master
branch and fully working in thecompleted
branch), but youcan also play with it in theFable REPL (see Samples, Elmish, Spreadsheet),which lets you edit and run F# in the browser.
Following the typical F# type-driven development style, the first thing we need to think aboutis the domain model. Our types should capture what we work with in a spreadsheet application.In our case, we have positions such asA5
orC10
, expressions such as=A1+3
and the sheetitself which has user input in some of the cells. To model these, we define types forPosition
,Expr
andSheet
:
1:2:3:4:5:6:7:8: |
|
APosition
is simply a pair of column name and a number. An expression is more interesting,because it is recursive. For example,A1+3
is an application of a binary operator on sub-expressionsA1
, which is a reference and3
which is a numerical constant. In F#, we capture this nicelyusing a discriminated union. In theBinary
case, the left and right sub-expressions are themselvesvalues of theExpr
type, so ourExpr
type is recursive.
The typeSheet
is a map from positions to raw user inputs. We could also store parsed expressions oreven evaluated results, but we always need the original input so that the user can edit it. To makethings simple, we'll just store the original input and parse it each time we need to evaluate thevalue of a cell. To do the parsing and evaluation, we'll later define two functions:
1:2: |
|
We will talk about these later when we discuss the logic behind our spreadsheet, but writing thetype down early is useful. Given these types, we can already see how everything fits together.Given a position, we can do a lookup intoSheet
to find the entered text, then we can parse itusingparse
to getExpr
and, finally, pass the expression toevaluate
to get the resultingvalue. We also see that bothparse
andevaluate
might fail. The first one will fail if theinput is not a valid formula and the second might fail if you reference an empty cell.
Now, all we have to do is to keep writing the rest of Excel until the type checker is happy!
I'm going to start by discussing the user interface and then get back to implementing the parsingand evaluation logic. For creating user interfaces, Fable comes with a great library calledElmish. Elmish implements a functional-first user interfacearchitecture popularized by the Elm language, which is also known asmodel view update.
The idea of the architecture is extremely simple. You just need the following two types andtwo functions:
1:2:3:4:5: |
|
The two types and two functions define the user interface as follows:
State
stores all the user interface state that you need in order to render it.Event
is a union of different events that can happen when the user interacts with the UI.update
is a function that takes an original state and an event and produces a new modified state.view
takes the state and generates a HTML document; it also takes a functionEvent -> unit
which can be used in event handlers of the HTML document to trigger an event.Conceptually, you can think that the application starts with an initial state, renders a page and,when some action happens and event is triggered, updates the state usingupdate
and re-rendersthe page usingview
. The key trick that makes this work is that Elmish does not replace thewhole DOM, but diffs the new document with the last one and only updates DOM elements that havechanged.
What state and events are there in our spreadsheet? As with the whole spreadsheet application,the first step in implementing the user interface is to define a few types:
1:2:3:4:5:6:7:8:9: |
|
In the state, we keep a list of row and column keys (this typically starts fromA1
, butwe do not require that), currently selected cell (this can beNone
if no cell is selected)and, finally, the cells of the spreadsheet. There are two events that can happen.TheUpdateValue
event happens when you change the text in the current cell; theStartEdit
event happens when you click on some other cell to start editing it.
Writing theupdate
function is quite easy - as with the main spreadsheet logic, we just needto write code until the type checker is happy!
In Elmish, theupdate
function is a little bit more complicated than I said above. Inaddition to returning new state, we can also return a list ofcommands. The commands areused to tell the system that it should start some action after updating the state. This canbe things such as starting a HTTP web request to fetch some information from the server.In our case, we do not need any commands, so we just returnCmd.none
:
1:2:3:4:5:6:7:8: |
|
The implementation uses thewith
construct, which creates a clone of thestate
recordand updates some of its fields. In the case ofStartEdit
, we set the active cell to thenewly selected one. In the case ofUpdateValue
, we first add the new value to the sheet(theMap.add
function replaces existing value if there is one already) and then set theCells
of the spreadsheet.
To construct the HTML document, Elmish comes with a lightweight wrapper built on top ofReact (although you can use other virtual DOM libraries too). The wrapper defines typedfunctions for creating HTML elements and specifying their attributes.
We'll first implement the mainview
function which generates the spreadsheet grid andthen discuss therenderCell
helper which renders an individual cell.
1: 2: 3: 4: 5: 6: 7: 8: 9:10:11:12:13:14:15: |
|
Here, we're using F# list comprehensions to generate the HTML document. For example, thelines 4-7 generate the header of the table. We create atr
element with no attributes(the first argument) containing a couple ofth
elements (the second argument). We'reusingyield
to generate the elements - first, we create the emptyth
element in theleft top corner and then we iterate over all the columns and produce a header for each ofthe columns. Thecol
variable is a character, so we first turn it into a string usingstring
before turning it into HTML content usingstr
function provided by Elmish.
The nice thing about writing your HTML rendering in this way is that it is composable.We do not have to put everything inside one massive function. Here, we callrenderCell
(line 12) to render the contents of a cell.
There are two different ways in which we render a cell. For the selected cell, we needto render an editor with an input box containing the original entered text. For all othercells, we need to parse the formula, evaluate it and display the result. TherenderCell
function chooses the branch and, in the latter case, handles the evaluation:
1: 2: 3: 4: 5: 6: 7: 8: 9:10:11:12:13: |
|
We test whether the cell that is being rendered is the active one using thestate.Active = Some pos
condition. Rather than comparing twoPosition
values,we comparePosition option
values and do not have to worry about the case whenstate.Active
isNone
.
If the current cell is active, we take the entered value or empty string and passit torenderEditor
(defined next). If no, then we try to get the input - if there isno input, we callrenderView
withSome ""
to render valid but empty cell. Otherwise, weuse a sequence ofparse
andevaluate
to get the result. We will look at both of thesefunctions below, when discussing how the spreadsheet logic is implemented. Bothparse
andevaluate
may fail, so we use the option type to compose them.Option.bind
runsevaluate
only whenparse
succeeds; otherwise it propagates theNone
result.We also useOption.map
to transform the optional result of typeint
into anoptional string which we then pass torenderView
.
So far, we have not created any handlers that would trigger events when somethinghappens in the user interface. We're finally going to do this inrenderEditor
andrenderView
, which are both otherwise quite straightforward:
1: 2: 3: 4: 5: 6: 7: 8: 9:10:11:12:13:14: |
|
InrenderView
, we create red background and use the#ERR
string if the value to displayis empty (indicating an error). We also add anOnClick
handler. When you click on the cell,we want to trigger theStartEdit
event in order to move the editor to the current cell. Todo this, we specify theOnClick
attribute and, when a click happens, trigger the event usingthetrigger
function which we got as an input argument for theview
function (and whichwe first passed torenderCell
and then torenderView
).
TherenderEditor
function is similar. We specify theOnInput
handler and, whenever the textin the input changes, trigger theUpdateValue
event to update the value and recalculateeverything in the spreadsheet. We also specifyAutoFocus
attribute which ensures that theelement is active immediately after it is created (when you click on a cell).
Now we have all the four components we need to run our user interface. We have theState
andEvent
type definitions and we have theupdate
andview
functions. To put everything together,we need to define the initial state, specify the ID of the HTML element in which the applicationshould be rendered and start it.
1: 2: 3: 4: 5: 6: 7: 8: 9:10: |
|
The initial state defines the ranges of available rows and columns and specifies that thereare no values in any of the cells (the demo embedded above specifies the initial cells forcomputing factorial and Fibonacci here). Then we usemkProgram
to compose all thecomponents together, we specify React as our execution engine and we start the Elmish application!
So far, we defined the domain model which specifies what a spreadsheet is using F# types andwe implemented the user interface using Elmish. The only thing we skipped so far is thespreadsheet logic - that is, parsing of formulas and evaluation. Completing these two is going tobe easier than you might expect!
First, let's have a look at how to evaluate formulas. In the beginning, we defined theExpr
type as a discriminated union with three cases:Number
,Binary
andReference
. Toevaluate an expression, we need to write a recursive function that uses pattern matching andappropriately handles each case. We'll start with a simple version that does not handle errorsand does not check for recursive formulas:
1: 2: 3: 4: 5: 6: 7: 8: 9:10:11:12:13: |
|
The function takes the spreadsheetcells
as a first argument, because it may need to lookupvalues of cells referenced by the current expression. It also takes the expressionexpr
andpattern matches on it. HandlingNumber
is easy - we just return the number.
HandlingBinary
is a bit more interesting, because we need to callevaluate
recursivelyto evaluate the value of the left and right sub-expressions. Once we have them, we use a simpledictionary to map the operator to a function (written using standard F# operators) and run thefunction.
Finally, when handling aReference
, we first get the input at the given cell, parse it andthen (again) recursively callevaluate
. This can fail in many ways - the cell might be emptyor the parser could fail. We improve this in the next version of our evaluator where thefunction returnsint option
rather thanint
. The missing valueNone
indicates thatsomething went wrong.
1: 2: 3: 4: 5: 6: 7: 8: 9:10:11:12:13:14:15:16:17:18: |
|
In case ofNumber
, we now returnSome num
. In this case, evaluation cannot fail.In case ofBinary
, both recursive calls can fail and we get two option values. To handle this,we useOption.bind
andOption.map
- both of these will call the specified function only whenthe previous operation succeeded, otherwise, they immediately returnNone
indicating a failure.If both the left and the right sub-expressions can be evaluated, we can then apply binary numericaloperator to their results. Handling ofReference
is similar - we sequence a number of operationsthat may fail usingOption.bind
.
Another interesting feature we added in this version is checking for recursive references. Todo this, theevaluate
function now takes thevisited
parameter which is a set of cells thatwere accessed during the evaluation. We add cells to the set usingSet.add pos visited
online 18. When we find a reference to a cell that we already visited (line 12), then we immediatelyreturnNone
, because this would lead to an infinite loop.
Finally, the last part of logic that we need to implement is the parsing of formulas entered bythe user into values of ourExpr
type. For this, we're going to use a very simple parser combinatorlibrary (which you can find in thefull source code).There are four key concepts in the library:
1:2:3:4:5: |
|
Parser<char, 'T>
represents a parser that takes a list of characters as the input. ItreturnsNone
if the parser cannot parse the input. Otherwise, the parser parses a value andreturns it together with the rest of the input. The fact that parsers do not have to consume theentire input makes it easy to compose them.
<*>
is a binary operator that takes two parsers; it runs the first parser first, getting avalue of type'T1
and then runs the second parser on the rest of the input, getting a value oftype'T2
. It succeeds only if both parsers succeed and then it returns a pair with both values.
<|>
is a binary operator that also takes two parsers, but they both have to recognise values ofthe same type. It tries to run the first parser and, if that fails, tries to run the second one.It succeeds if either of the parsers succeed and returns whatever the successful parser returned.
Finally,map
is a function that transforms the value that a parser produces. Given a parser oftypeParser<'T>
and a function'T -> 'R
, it returns a parser that runs the original parser and,if that is successful, applies the function to the result.
The following snippet shows how we use these three ideas to create simple parsers to recogniseoperators, references and numbers:
1:2:3: |
|
Thechar
function creates a parser that recognises only the given character (and then returns it as theresult). Thus, theoperator
parser recognises the four standard numerical binary operators and acceptsno other characters. Thereference
parser recognises a letter followed by a number. This returnsachar * int
pair which we turn into theReference
value ofExpr
using themap
function.Parsing a number is even easier - we just run the built-ininteger
parser and wrap it inNumber
.Note that the type ofreference
andnumber
is now the same -Parser<char, Expr>
. This means thatwe can compose them using<|>
to create parser that recognises either of the two expression types.
Finishing the rest of the parsing is a bit more work, because we need to handle parentheses as(1+2)*3
and also ignore whitespace, but the concepts are the same:
1:2:3:4:5:6:7:8:9: |
|
To deal with recursion, the library allows us to create a parser usingslot
, use it, and then definewhat it is later usingexprSetter
. In our case, we defineexpr
on line 1, use it when definingbrack
(line 3) and then define it on line 9. This is a recursive reference;exprAux
canbebinary
, which containsterm
, which can bebrack
and that, in turn, containsexpr
.
The only other clever thing in the snippet are the<<*>
and<*>>
operators. Those behave like<*>
, but return only the result from the parser on the left or right (wherever the double arrow points).This is useful, because we can writeanySpace <*>> expr <<*> anySpace
to parser expression surroundedby whitespace, but get a parser that returns just the result ofexpr
(we do not care what the whitespacewas).
Finally, we define a formula which is=
followed by an expression and an equation - that is, the thingthat you can type in the spreadsheet - which is either a formula or a number.
1:2:3: |
|
Theparse
function defined on the last line lets us run the mainequation
parser on a given input.It takes a sequence of characters and producesoption<Expr>
, which is exactly what we've used earlierin the article.
In total, this article showed you some 125 lines of code. If we did not worry about nice formattingand skipped all the blank lines, we could have written a simple spreadsheet application in some 100lines of code! Aside from standard Fable libraries, the only thing I did not count is the parser combinatorlibrary. I wrote that on my own, but there are similar existing libraries that you could use (thoughyou'd need to find one that works with Fable).
The final spreadsheet application is quite simple, but it does a number of interesting things. Itruns in a web browser and you can scroll back to the start of the article to play with it again!On the technical side, it has a user interface where you can select and edit cells, it parses theformulas you enter and it also evaluates them, handling errors and recursive references.
If you enjoyed this post and want to learn more about F# and also Fable, joinourF# FastTrackcourse on6-7 December inLondon at SkillsMatter. We'll cover Fable, Elmish, butalso many other F# examples. Get in touch at@tomaspetricekor emailtomas@tomasp.net for a 10% discount for the course,or if you are interested in custom on-site training.
I like this example, because it shows how a number of nice aspects of the F# language and also theF# community can come together to provide a fantastic overall experience. In case of our spreadsheet,this includes:
Fable makes it possible to compile F# to JavaScript, but more importantly,it also gives us access to the JavaScript ecosystem. Fable follows the pragmatic style offunctional-first F# programming. This makes it possible to integrate with libraries such as Reactand build different architectures on top of them.
The Elm architecture, as implemented bythe Elmish library,is a fantastic way to write functional-first user interfaces. All we had to do to implement thespreadsheet user interface was to define types for the state and events and then implement theupdate
andview
functions.
Finally, the example also used compositionality of functional programming in two ways. First, anexpression is elegantly expressed by a recursive typeExpr
which can consist of otherExpr
values. Second, we composed a parser for spreadsheet formulas from just a few primitives usingjust two operators,<|>
and<*>
.
If you want to have a look at the complete source code, you can find itin my elmish-spreadsheetrepository on GitHub. The repository is designedas a hands-on exercise where you can start with a template, complete a number of tasks and endup with a spreadsheet, but there is alsocompleted
branch where you find the finished source code.You can also edit and run the code in your browser using theFable REPL(you'll find it under Samples, Elmish, Spreadsheet),
Published: Monday, 12 November 2018, 1:58 PM
Author: Tomas Petricek
Typos:Send me a pull request!
Tags:f#,functional,training,fable