How Programming Languages Change How You Think
Tags: fsharp, dotnet, programming, csharp
Published: 2020-12-27 06:27:52

---
title: How Programming Languages Change How You Think
published: true
date: 2020-12-27 06:03:23 UTC
tags: fsharp, dotnet, programming, csharp
cover_image: https://i2.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-22.png?fit=768%2C415&ssl=1
canonical_url: https://killalldefects.com/2020/12/27/how-programming-languages-change-how-you-think/
---

This might be a weird article.

A few years ago I saw the terrific movie “Arrival” and it changed how I look at language. A little later, I encountered F# for the first time and it changed the way I look at _programming_ _languages_.

In this article I’m going to walk you through the basics of some of the theories touched upon in Arrival and then pivot into the role of language in programming. We’ll compare and contrast a number of languages and see how they impact how we think about solving problems in software engineering before we do a deeper dive into the F# programming language.

I told you this might be a weird article.

* * *

The first half of the article will cover a wide range of languages while the second half will focus on F# and how the structure and syntax of that languages impacts our approaches to programming.

This article will be of most interest to those coming in with less experience in functional programming or F#. The ideal reader will have experience with C#, Java, JavaScript, TypeScript, Python, or similar languages.

## The Impact of Language on Thought

Let’s start with a brief journey into science fiction.

_Note: This section contains mild spoilers on the first hour of the plot in Arrival, most of which could be gleaned from the film’s [trailer](https://www.youtube.com/watch?v=tFMo3UJ4B4g)._

The 2016 film [Arrival](https://en.wikipedia.org/wiki/Arrival_(film)) is a science fiction drama movie starring Amy Adams and Jeremy Renner. It’s the kind of movie that I love but my wife sleeps through – a slower-paced movie where a group of scientists try to communicate with aliens who have arrived over various parts of the world.

The key focus of Arrival is _language_ and specifically how language impacts the way we form thoughts and even perceive reality.

The aliens that the scientists encounter mainly communicate via _logograms_ containing entire sentences in a circular pattern as pictured below:

![Arrival Logograms | Pattern tattoo, Tattoos, Arrival movie](https://i1.wp.com/i.pinimg.com/originals/89/f5/fd/89f5fd406009126a0fab3b445daf7334.jpg?resize=364%2C364&ssl=1)

There’s a beautiful sequence roughly 55 minutes into the film where they discuss the alien language and its problems at length and it includes this quote from one of our main scientists:

> “If you immerse yourself into a foreign language then you can actually rewire your brain”
> 
> <cite>Arrival, 2016</cite>

The sequence goes on to discuss [the Sapir-Whorf hypothesis](https://en.wikipedia.org/wiki/Linguistic_relativity) and if the language you speak can alter how you think or, in the case of the characters in Arrival, how they perceive reality.

As you might expect, the film enters the territory of mind-bending science fiction shortly thereafter, but it’s a very good film if that’s your cup of tea.

* * *

While I enjoyed the film and its concepts, it got me thinking about programming and how different _programming language_s might alter the way we think about application development.

This is a thought that stuck with me and resurfaced as I delved deeper into functional programming.

## The Impact of Programming Language on Thought

Let’s take a quick tour of a few different programming languages. We’ll look at some sample code from each one and speculate at the ways of thinking that they might encourage or discourage.

_Disclaimer: I am including basic information on several languages I have not extensively programmed in to offer a healthy variety of syntax. I will be relying on some speculation for these as well as my own personal experiences with the languages my knowledge and experience are deeper in._

### C# #

C# is an _imperative_ programming language built to support object-oriented programming (OOP) with syntax inspired by C++ and Java. Like F# and Visual Basic, C# runs on .NET and can interact with other .NET programming languages.

Let’s look at some sample C# code from a game project of mine from years back:

![](https://i2.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-17.png?resize=495%2C435&ssl=1)

Here we have a class from a game context that contains an ApplyDamage method. Code flows from top to bottom and may or may not enter if statements for conditional logic before it returns a number indicating the damage dealt.

This type of programming is very typical for object oriented languages despite the simplified example here and encourages the following types of behavior:

- Thinking about the system in terms of individual objects
- Focusing on if statements which may or may not need to execute
- Adding properties, methods, and inheritance to manage complexity as things grow

I should note here that although C# was built as an object-oriented interpreted language, it is shifting to allow the language to support functional programming approaches like F#.

### JavaScript

JavaScript is a function-oriented language built originally for the browser. JavaScript has since grown to support full-stack application and server development.

Here’s a snippet of JavaScript code from a _different_ hobbyist game project of mine (seeing a pattern yet?):

![](https://i0.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-18.png?resize=768%2C383&ssl=1)

This JavaScript code is similar to our C# example above in that it represents an imperative series of commands that the program will run.

There are some notable differences to C#, however.

Most notably, JavaScript is loosely typed. This means its variables don’t have a type defined in advance and can be reused for things of different types. Objects can have new properties dynamically added or even removed as the program runs. Functions can also be called with any number of parameters, including less than or more than the function expects.

As a result, JavaScript programs tend to feel a bit more loose than strongly-typed programming languages. This additional freedom creates some unique problems which additional syntax such as the rest and spread operators (…) among others have helped alleviate.

### TypeScript

I hesitate to include TypeScript since TypeScript is just a different way to generate JavaScript, but I think it’s worth discussing briefly using code from – you guessed it – a different game project of mine.

![](https://i2.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-23.png?resize=770%2C241&ssl=1)

TypeScript is really JavaScript plus some _optional_ type declarations. The TypeScript compiler takes TypeScript code and compiles it down to working JavaScript code which is then understandable by the browser.

Because of this, TypeScript isn’t much different than JavaScript, but it does add type declaration statements.

It turns out that type declarations are actually a pretty big deal to how you think about your code. Instead of wondering what type something is or having to rely on accurate documentation, you can now see the type declaration next to the variable or parameter. This is a nice touch, however it does have drawbacks.

Because TypeScript relies on the programmer to accurately define the types, it pushes you towards types that are easy to represent via standard syntax. This in turn discourages you from passing functions around as parameters.

If you were to declare a parameter that is a function that takes in a Number and returns a Boolean, that syntax is _possible_ but still difficult to remember, write, and read, so you naturally tend to do it less frequently.

### Python

Python is another imperative language like C# or JavaScript, but it’s syntax is notably different:

![](https://i0.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-21.png?resize=768%2C383&ssl=1)

_Code example taken from [The Algorithms](https://github.com/TheAlgorithms/Python/blob/master/strings/swap_case.py)_

As someone who has only done bits of Python programming, I can’t speak too much to how Python changes your way of thought, except to point out how _elegant_ the syntax feels compared to other languages.

It’s a very minimal style requiring indentation over brackets to define scopes. This reduces the level of noise in the code and helps you focus on the logic.

In my experience, this style of minimalism causes me to emulate it with very concise functions that call out to other functions, resulting in code that is nearly as compact as F#, but significantly more readable.

I also should point out a comparison to JavaScript and TypeScript with Python: Python allows you to add a [type hint](https://kishstats.com/python/2019/01/07/python-type-hinting.html) if you choose to do so (and is pictured in the code above). However, this feature was added since I last worked with Python and I cannot talk much about it as a result.

### Go

Go (also called GoLang) is a more recent development and represents another statically typed imperative programming language.

Let’s look at its syntax because it’s a bit different in a few aspects beyond just where braces and brackets are placed:

![](https://i2.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-22.png?resize=768%2C416&ssl=1)

_Code example taken from [The Algorithms](https://github.com/TheAlgorithms/Go/blob/master/sorts/bubblesort.go)_

Go has a few syntax niceties I’ve not bumped into in other languages yet.

The [for keyword](https://golangdocs.com/for-loop-in-golang) is much more flexible, allowing for infinite loops if needed. Additionally, Go uses := as a shorthand for _declare and assign_, which keeps noise to a minimum. Finally, we see a quick way of swapping two values with the , and = operators.

I cannot write much how Go might impact how we think about writing applications, but I’d be curious about the experiences of those of you who have worked more with Go.

My initial reaction is that it takes a lot of the elegance from Python and applies it to syntax similar to C#, Java, and JavaScript’s, and I’m curious how far that additional “syntactic sugar” goes in terms of changing how you think about problem solving.

### F# #

Everything I’ve covered so far has primarily been an imperative programming language. F#, by contrast, is a _functional_ programming language, which relies on entirely different patterns of code:

![](https://i0.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-20.png?resize=770%2C141&ssl=1)

_Code example taken from [The Algorithms](https://github.com/TheAlgorithms/F-Sharp/blob/main/Algorithms/Strings/CheckAnagrams.fs)_

F#, like C#, is _strongly typed_ and those types are enforced by the compiler. However, more type information is _inferred_ by the F# compiler and so actual type keywords are only needed sparingly. As a result, **F# syntax is able to work more seamlessly with complex types,** since the need to represent those types in syntax is significantly reduced.  
  
F# syntax often deals with “piping” things from function to function to bring about an expected result.

We’ll take a more in-depth look at F# in the next section and examine a few cases involving piping before exploring a wider range of ways its different syntax may impact how you think about problem solving in code.

_Note: F# is not the only modern functional programming language, but out of my familiarity with the F# language and the fact that this article is technically part of the community [F# advent 2020 series](https://sergeytihon.com/2020/10/22/f-advent-calendar-in-english-2020/), we’ll zero in F# for the remainder of the article._

### Other Languages

If you’d like to look more into the syntax related to many of the currently used programming languages, I recommend you check out [The Algorithms on GitHub](https://github.com/TheAlgorithms) for an open source set of examples including some other functional programming languages.

I’d also love to see your thoughts on how programming languages have shaped how _you_ think about programming, so please leave a comment as well.

## How F# Changed How I think about Programming

With this overview of languages aside, let’s dive deeper into the F# language and how its features change the way we approach code.

### F# is not C# #

When I first tried to learn F#, it was a difficult experience for me. It was my first functional programming language and terms such as monads, partial application of functions, and higher-order functions made my journey a difficult one.

Adding to that burden, as I learned F#, I was focused on “How do I write this C# code in F#?” so my first attempts at F# tried to create strong types with mutable state like you’d do in a C# program.

While F# _can_ do that, it’s not what F# is about. F# isn’t about creating _classes_ with mutable state and traditional members but about writing _functions_ and composing those functions into solutions to larger problems.

In object-oriented languages we focus on encapsulating logic in cohesive objects and calling methods on those objects in a specific sequence. In other words, the classes are the stars of the show and their methods help things work.

F# encourages puts the focus on individual functions and pushes you towards _immutable_ state and chaining functions together. The functions are the main attraction and the types that support them are left as minimal as possible (though F#’s typing system is very powerful and flexible).

### Thinking in Terms of Pipes

When I think of F# applications, I picture a series of pipes connected to each other – each one meticulously designed to have exactly the correct output given a specific input and have no other side effects. This type of function is commonly called a _[pure function](https://en.wikipedia.org/wiki/Pure_function)_.

The individual pipes (or functions) are small and highly specialized, but together they make a very capable application.

![gray commercial machine](https://images.unsplash.com/photo-1513828583688-c52646db42da?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80)<figcaption>Photo by <a href="https://unsplash.com/@spacexuan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Crystal Kwok</a> on <a href="https://unsplash.com/s/photos/pipes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

F# as a language is very good at chaining things together thanks to its [specialized operators](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/) such as the |> or “pipe” operator which takes the value on the left and makes it the last parameter to the function on the right.

Just looking at the presence of this one isolated operator in F# a multitude of things become easy in F# that would be harder in a language such as C#.

* * *

For example, look at the following F# code:

```fsharp
watermelon |> SliceOpen |> RemoveSeeds
```

This takes whatever watermelon is and passes it as a parameter to the `SliceOpen `function and then takes the result of that call and passes it in to the `RemoveSeeds `function.

We could simplify this further in F# by using the `>>` operator to compose a `SliceAndRemoveSeeds `function from the `SliceOpen `and `RemoveSeeds `functions like this:

```fsharp
let SliceAndRemoveSeeds = SliceOpen >> RemoveSeeds
watermelon |> SliceAndRemoveSeeds
```

If we wanted to do the same thing in C# code, we’d have to write the following:

```cs
var slicedWatermelon = SliceOpen(watermelon);
var preppedWatermelon = RemoveSeeds(slicedWatermelon);
```

Admittedly, we could simplify this a bit by writing:

```cs
var preppedWatermelon = RemoveSeeds(SliceOpen(watermelon));
```

This _does_ work, but you can start to feel the language fighting you a little and now need to learn to read your code from the inside out. F# code is much more of a sequential and minimal syntax (though it does take some getting used to), so this kind of functional chaining code becomes more natural in F# vs C#.

### Parameter Order

Because the pipe operator always passes in the result as the last parameter to the function it is piped into, we now need to start paying attention to the order in which we declare parameters.

The pipe operator is not alone in this regard either since things like [partial application of functions](https://fsharpforfunandprofit.com/posts/partial-application/) also have an impact on how you order parameters:

```fsharp
let AddNumbers x y = x + y
let AddTwo = AddNumbers 2
let five = AddTwo 3
```

Here we define `AddTwo `as a function that calls `AddNumbers `with the first parameter of 2 and the second parameter unspecified. Next, we can call `AddTwo `with a second parameter of 3 which ultimately adds 2 and 3 together.

The resulting effect is a somewhat new and unusual feeling of needing to think about your parameters and understand which one ought to be last.

### Code Order

The F# compiler’s intelligence comes at a cost: In F# not only do you have to pay attention to which function is defined first within a file in order for things to compile, you also need to explicitly set a compilation order for individual files inside of your project.

For example, in the picture below, the `Gasses.fs` file can reference anything in `Utils.fs` and `Positions.fs`, but cannot reference anything in `GameObjects.fs` or below.

![](https://i1.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-24.png?resize=282%2C364&ssl=1)

This process of needing to consider file and function order initially seems like an irritant. However, it has some pleasant side effects.

Because functions are now order dependent it becomes impossible to create infinite loops of function A calling function B which calls function A again and your module dependencies are now much easier to visualize. The compiler effectively ensures your dependencies only flow in a specific direction. Entire tools such as [NDepend](https://www.ndepend.com/) have been built around trying to enforce this concept in other codebases.

### Intelligent Typing

All of these features I’ve described above are mere syntax sugar to some of F#’s true strengths, however.

F# offers some truly interesting mechanisms for declaring types. Take this GameObjectType definition from a side project of mine:

![](https://i2.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-25.png?resize=490%2C219&ssl=1)

This is similar to a [C# enum](https://www.youtube.com/watch?v=LUtEwh94xcA&t) but offers some additional bits of logic. Here a game object can be any number of things, but a few things have additional data associated with them. An air pipe needs to track the mixture of gasses flowing through it, for example, and a door is either going to be left to right or top to bottom in a 2D world and will either be open or closed.

In an object-oriented language we might use inheritance and define subclasses for these doors and pipes, but in many cases this might be overkill – particularly when we want our focus to be on concise, reusable functions instead of powerful objects.

We can then `match `off of the object type in F#:

![](https://i0.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-26.png?resize=770%2C153&ssl=1)

This is a case where F#’s syntax has pushed us away from inheritance and towards using an intelligent _match_ keyword and expressions to handle the various cases (with \_ being a wildcard meaning anything else that didn’t match).

As a result, our focus as developers remains on the functions instead of being on creating powerful types. This in turn makes us focus on how our functions _fit together_.

### Options over Nulls

Nulls have famously been called [the billion dollar mistake](https://hackernoon.com/null-the-billion-dollar-mistake-8t5z32d6). While I’m not sure I go that far, it’s worth pointing out F#’s handling of nulls to the uninitiated.

Here’s a small F# function that tries to find a 2D game tile at a specific position inside of another tile layer. It will either find a tile or it won’t, and if it does, it needs to merge that tile on top of the current tile:

![](https://i0.wp.com/killalldefects.com/wp-content/uploads/2020/12/image-27.png?resize=770%2C121&ssl=1)

F# chooses to handle nulls primarily with the _option_ type. An option is either going to be _some_ value or it’s going to be _none_. Option could be considered to be a generic type in C# contexts and will never be null itself.

The F# compiler insists that you use specific ways of getting the value out of an option and explicitly makes you handle the possibility of an option being _none_. This forces you as a developer to explicitly handle these cases and reduces the odds of you accidentally forgetting to handle nulls.

In general, F# will encourage you towards working with empty lists or options over explicit null values and the compiler slaps you in the face with things you may have forgotten. Not everyone loves a strong and opinionated compiler (trust me, I know from advocating for TypeScript in the JavaScript world), but F#’s compiler catches mistakes I didn’t even know I had, and that’s very valuable to me as a developer.

_It should be noted that other languages are also starting to adopt these approaches, most notably with [C# adding support for explicit null checking](https://killalldefects.com/2019/09/13/safer-code-with-c-8-non-null-reference-types/) as an opt-in feature._

## What F# has to do with George Orwell’s 1984

Before we close, let’s look briefly at another work of fiction and it’s thoughts on language: George Orwell’s classic novel [1984](https://en.wikipedia.org/wiki/Nineteen_Eighty-Four).

![1984 steel decor](https://images.unsplash.com/photo-1523981354642-fa01e6c05c77?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80)

_Photo by [Viktor Forgacs](https://unsplash.com/@sonance?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/1984?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_

I read this book a number of times in my youth, and one of the most striking aspects of it was language and how the “Ministry of Truth” in the book had revised speech to make undesirable concepts harder to represent. For example, words such as “bad” were replaced with things like “ungood”.

It’s a striking picture and example, regardless of whether you were excited to read 1984 in school or not, and it’s come to represent how I think about the F# language.

For me the key beauty of the F# programming language is that **F# makes invalid states harder to represent**.

In programming, every decision – including those made by our language designers – comes with tradeoffs. Things that are easy we tend to do and things that are harder to represent we tend to avoid.

F#’s functional syntax comes with a hefty learning curve and a need to almost re-learn programming in a different context, but it does make invalid states harder to represent at the compiler level. Whether that price is worth paying is up for you and your team to decide.

Additionally, not all problems _should_ be solved by a functional programming language. Most of programming is maintaining existing code and not all code has the complexity needed to necessitate functional programming languages. Some problem domains also have a lot of unique information and logic that truly does belong in types.

## Closing

Whichever programming language you choose to use in your project, it should serve your purpose and it should be a conscious decision on your part.

When you start a new project ask yourself these things:

- What does this language make easy for me?
- What does this language make harder?
- How hard is it to find or train developers who can write and maintain this language?
- How much training would my team need to use this language?
- How much support on this language can I expect from official and community channels in the future?
- How hard is it for me to use this code to work with other existing code our organization uses?
- How much does this language provide for me and what would I need to add myself?
- Do I like the type of code this language encourages me to write?

We need to start examining the tradeoffs of language choices and what patterns our languages are pushing us into, because these choices may matter more than you realize.

_This article is part of the [F# Advent 2020](https://sergeytihon.com/2020/10/22/f-advent-calendar-in-english-2020/) series. Check that series out for more articles on F# from members of the community._

*The post [How Programming Languages Change How You Think](https://killalldefects.com/2020/12/27/how-programming-languages-change-how-you-think/) appeared first on [Kill All Defects](https://killalldefects.com).*