A Brief Introduction to F# for Object Oriented Developers

samwalpole.com
7 min read
fairly easy
Recently I've been learning how to write code in F#. For those who haven't heard of it, F# is Microsoft's/.NET's answer to a functional-first programming language. My motivation was to learn a functional programming language that would make coding fo...
r scientific computing and data analysis more expressive, concise, and maintainable, all while fitting seamlessly into the .NET ecosystem that I already know and love. F# fits that bill perfectly.

Why Functional Programming?

For an object oriented programmer, the idea of functional programming can be a little foreign at first. We're used to applications in which everything is an object and the application works by changing the state of those objects (mutation) over time. In contrast, functional programs consist of values and functions, and the application works by applying these functions to values in order to produce new values.

This might sound similar to methods in an object oriented style, but there are two key differences:

Values cannot be modified (they are said to be immutable). Instead, operations create and return new values. Functions should be pure, meaning that a given input always produces the same output. This is in contrast to a class method, in which some internal state of the class might have an effect on the output of the method.

Let's have a look at this in a code example, in which we want to raise an employee's salary by a given factor:

public class Employee { public string Name { get ; set ; } public float Salary { get ; set ; } } public class SalaryRaiser { public float Factor { get ; set ; } public void RaiseSalary ( Employee employee ) { var raise = employee.Salary * Factor; employee.Salary += raise; } } var employee = new Employee { Name = "Bob" , Salary = 12345.67F }; var raiser = new SalaryRaiser { Factor = 0.05F }; raiser.RaiseSalary(employee);

// F# Functional Example type Employee = { Name: string; Salary: float } let factor = 0.05 let calculateSalary employee factor = // function is pure - factor is now a parameter let raise = employee.Salary * factor // new employee record returned { employee with Salary = employee.Salary + raise } let employee = { Name = "Bob"; Salary = 12345.67 } let updatedEmployee = calculateSalary…
Read full article