F# Introduction from a C# Developer

February 18, 2022    Development DotNet F# Functional

F# Introduction from a C# Developer

I’ve been a C# and Javascript/Typescript developer for 14+ years, some PHP before that. I’ve been blissfully avoiding other approaches/languages (there’s too much to learn, my energy is limited, I have 4 kids, etc). Over the last few years, functional programming has been coming up more often and intriguing me more.

We read Pragmatic Programmer together at Omnitech in 2021. My quote in that article was “The biggest “eye-opener” for me was about transforming programming, where you take input data and transform it into an output. Thinking of the data as a “mighty river” opened me to new thinking.” See Tip 49 “Programming is about Code, but Programs are about Data”. Use transformations.

I kept hearing Gene Kim talk about Clojure (in the Unicorn Project) and in his IT Revolution podcasts. I heard a snippet of him talking about his love letter to Clojure . These also got me wondering what I was missing.

The real hook for me into functional thinking, was listening to the Gene Kim and Scott Haven conversations in episode 22 and 23 and then watching Scott Haven at DOES 2019. Forging a Functional Enterprise: How thinking Functionally Transforms Line-of-Business Applications . This “blew my mind”.

I kept thinking: Can this really be achieved? Can it be applied to small projects?

Why F#/Functional Programming?

F# is in the DotNet ecosystem , so it was a natural fit for me to try. You can reference existing .Net libraries and methods you are already familiar with. It works great in Visual Studio and VS Code.

This reasoning is quoted from Fsharp for Fun and Profit . Please read more of the details there. There is also a series of posts that are helpful.

“Although F# is great for specialist areas such as scientific or data analysis, it is also an excellent choice for enterprise development. Here are five good reasons why you should consider using F# for your next project.”

  1. Conciseness
  1. Convenience
  • less boiler plate code
  1. Correctness
  • things are immutable by default, avoiding problems no more hunting for what changed that property on your public setter property
  • “In addition, you can often encode business logic using the type system itself in such a way that it is actually impossible to write incorrect code or mix up units of measure, greatly reducing the need for unit tests.”
  1. Concurrency
  • Async programming is easy with the built in libraries. So is parallelism with the actor model
  1. Completeness
  • the F# language is complete

Other Reasons

  • Function-oriented rather than - object-oriented
  • Expressions rather than statements
  • Algebraic types for creating domain models
  • Pattern matching for flow of control

from https://fsharpforfunandprofit.com/posts/key-concepts/

Benefits of Functional Programming

  • Declarative - composition and pipes
  • Separate your domain logic from your I/O (Scott Haven and Clean Architecture )
  • New way of thinking
    • don’t just stay into your Object Orientated Programming thinking
  • functions are first class citizens
  • Immutable - this helps avoid the “who’s filling my cup” problem

Gene Kim’s by reference ~ From Gene Kim’s love letter to Clojure

Core Principles & Philosophy

  • functions are things
    • standalone
    • reusable
    • Transformation railroad track (input —> output)
    • most tools are function transformers
  • composition is every where like Legos
    • Lego philosophy
    • fit together, reusable

Philosophy

  • Design functions that do one thing well
  • Design functions to work together
    • expect the output of every function to become the input to another, as yet unknown, function
  • use types to ensure that inputs match outputs

Can compose all the way up to [[Functional Architecture]]

  • even a web application#

from NDC 2019 - F# The Functional Toolkit - Scott Wlaschin 10/19/2021

Features I’ve liked

  • It’s .Net. The tools all work, and we can reference standard Dotnet Nuget Packages
  • I’ve enjoyed piping from function to function to transform data. It was easier
  • The type inference is really neat, but is taking some time to get used to
  • I’m glad things are immutable. It forces you to approach coding differently than objects with public setters. This is a really good thing and aligns well with the DDD approach.
  • The built in units of measure has been very helpful on my current project. We have a lot of gallons and liquid measurements that need converting.

Note: the .fsproj needs to have all the files listed and in the correct order for the complier.

Code Examples

I’ve put some code examples on Github that I used in my presentation at work. I’ve taken them from the links I’ve listed. There are better places to learn from and see code sample.

Where to start learning?

Unit testing

I have a lot to learn in this area. I have some tests in XUnit and wrote them in the normal way. It was difficult to setup objects the way I wanted to, but that is mostly my limited experience.

I’ve heard of Property Based Testing with FS Check and need to figure this out. You can have the test generate random data to throw at code. It’s similar to [DataRow()] or [Theory], but you don’t have to think of all the permutations.

That link has a presentation “The lazy programmer’s guide to writing 1000’s of tests” that is on my list to watch.

Build HTML Example

The Giraffe.ViewEngine is a UI framework which uses traditional F# functions and types to build rich HTML or XML based web views. ~ their about in Github .

I’ve used this to generate an HTML report. Here’s an example from their Github readme:

let indexView =
    html [] [
        head [] [
            title [] [ str "Giraffe Sample" ]
        ]
        body [] [
            h1 [] [ str "I |> F#" ]
            p [ _class "some-css-class"; _id "someId" ] [
                str "Hello World"
            ]
        ]
    ]

HTML parsing

https://fsprojects.github.io/FSharp.Data/library/HtmlParser.html

let title = 
    html.Descendants ["div"]
    |> Seq.filter(fun d -> 
        d.TryGetAttribute("class")
        |> Option.map (fun cls -> cls.Value()) = Some "title"
    )
    |> Seq.head

// new way
let title = 
    html.CssSelect "div.title"
    |> Seq.head

Building Web Server Applications: Fable

Fable . “Fable is a compiler that brings F# into the JavaScript ecosystem”. They have an online repl for experimenting.

I haven’t used it, but it looks cool.

Microsoft has listed more F# for web development links.

Functional System Thinking

Scott Haven’s presentation was my first taste. Watch it (it’s only 30 minutes long)! I enjoyed the conversation with Gene Kim afterwards

https://itrevolution.com/the-idealcast-episode-22/

DOES 2019 - Forging a Functional Enterprise

and https://itrevolution.com/the-idealcast-episode-23/

I’m hoping to read Domain Modeling Made Functional by Scott Wlaschin after a recommmendation.

So much more to learn

I spent about a week on my first task in F# (and also learning a new domain/business). I was glad to have the time to both struggle, try things, watch and read to learn. There is still a lot I don’t know well.

I need to learn more about the type inference, more of the base concepts and the special character functions (>> for composition, etc). I also need to learn how to think in the functional way, instead of trying to apply my Object Oriented thinking.

I hope I get many opportunities to use F# and will be looking for times to use it.

I also wonder how often I’ll get to use F#. I’m on a project that uses it, but after that I don’t know. I imagine it being hard to convince someone to start a new project with F#, since most of the people I know are familiar with C#.

More Resources

  1. https://github.com/adelarsq/fsharp-cheatsheet#MappingFunctions
  2. F# for C# Programmers - Scott Wlaschin at NDC 2017
  3. NDC 2019 - F# The Functional Toolkit - Scott Wlaschin 10/19/2020
  4. F# Functional Programming in 40 Minutes • Russ Olsen • GOTO 2018
  5. https://atlemann.github.io/fsharp/2021/12/11/fs-crypto.html
  6. https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/


comments powered by Disqus
Watch the Story for Good News

Please consider using Brave and adding me to your BAT payment ledger. Then you won't have to see ads!

Use Brave

Also check out my Resources Page for referrals that would help me.