Is C# Getting More Functional?


Looking at the set of features introduced in C# 7, I am thinking –

Is C# trying to follow the footsteps of Scala (a functional language that compiles into JVM bytecode)?

To answer the question let’s look at the features that have been introduced.

I got a chance to work with Scala while working at agoda (It was my first introduction to functional programming and I found it quite natural and more mathematical). Scala is a great programming language and has very concise and expressive syntax. Now coming back to C# and the features that have been introduced. We will take them one at a time so let’s start with something that’s my favorite.

  1. Embedded/Local functions: Okay so what is a functional language? well a functional language is a language where functions can be treated like data – what this means is that you can:
    1. Pass a function as a parameter to another function (already supported through lambdas in C# since version 3.0).
    2. Return a function as output from a function (Already supported through delegates since or before version 3.0 – using Action<T> and Func<T>).
    3. Declare and instantiate a function inside another function like any other variable: Think about the situations where you needed to create a separate function (for the sake of readability or may be for recursion) so that you can use it inside just one function.

C# 7.0 allows you to do something like this:

Function1

This was already available in functional languages like JavaScript and Scala but was missing from C#, you could however do something like this (and the above code is just a syntactic sugar for the below:

Function2

OR

Function3

Now depending on your taste and preferences (and the human tendency to stay in comfort) you might find the below two examples more understandable but if you look at the fact that the function Fib is not being used anywhere else besides being called from the Fibonacci function, the existence of the Fib function in the class (even if it’s private) is not justified.

The same can be rewritten as (and this is as short as it can be):

Function4

Now you might say that the above is more concise (in terms of number of lines of code) and may be more understandable but still the Fib function can never be defined inside the Fibonacci function up until now, if you try to do something like this (before C# 7.0) you would get big red lines of horror:

Function5

You must have figured out by now that recursion was not supported in lambdas and hence the squiggly below Fib call, now the below function is perfectly valid in C# (because it’s a variable and not a function):

Function6

Here the value “i” can reference itself in the add (+) operator call (binary operators are also functions with LHS and RHS as input parameters and return an output). So C# was treating data and functions differently.

2. Deconstruction: We have all seen constructors and they have been around since ages. Deconstructors are a mechanism for breaking down the complex types as combination of simple or other complex types. “Deconstruct” is similar to “unapply” method of Scala. Deconstruction is especially helpful in pattern matching (another great feature of Scala and now C# as well – saving it for another article). Deconstruction allows you to do something like:

Function7

So you can create methods that can reverse the construction process and extract values (simple or complex) out of objects. Without this you would have to do something like this:

Function8

Or if your “Point” class code is inaccessible and it is sealed then:

Function9

You can make it even more concise by doing something like:

Function10

This is quite concise and subtle but this still doesn’t beat the simplicity of the new deconstruction feature. Moreover you can add discards like this:

Function11

So the value of “Y” would simply be discarded.

We will discuss more of these in the next article.

Other posts

  • Building Your First Neural Network with TensorFlow – Deep Learning 2

    Building Your First Neural Network with TensorFlow – Deep Learning 2

    Neural networks are a fundamental concept in deep learning and are used for a wide range of applications such as image and speech recognition, natural language processing, and much more. In this article, we will walk you through the process of building your first neural network using TensorFlow, a popular open-source machine learning library. We'll…

  • Introduction to Deep Learning with TensorFlow – Deep Learning 1

    Introduction to Deep Learning with TensorFlow – Deep Learning 1

    In this article, we provide an introduction to deep learning with TensorFlow. We cover what deep learning is, what it can do, why TensorFlow is a great choice for deep learning, and an overview of TensorFlow itself. We also explore the different types of neural networks used in deep learning, and demonstrate how to build…

  • How To: Set Up PyTorch with GPU Support on Windows 11 – A Comprehensive Guide

    How To: Set Up PyTorch with GPU Support on Windows 11 – A Comprehensive Guide

    Introduction Hello tech enthusiasts! Pradeep here, your trusted source for all things related to machine learning, deep learning, and Python. As you know, I’ve previously covered setting up TensorFlow on Windows. Today, I’m excited to bring you a detailed guide on setting up another popular deep learning framework, PyTorch, with GPU support on Windows 11.…

  • Solving a Complex Logistics Optimization Problem using the Pulp Library in Python – Part 4

    Solving a Complex Logistics Optimization Problem using the Pulp Library in Python – Part 4

    In this article, we demonstrate how to solve a logistics optimization problem using the Pulp library in Python. By defining the variables, objective function, and constraints, and using the solve method to find the optimal solution, we are able to minimize the total cost of transportation while satisfying the constraints. This article concludes the multi-part…

  • Linear Programming in Python using PuLP – Part 3: Optimizing Investment Portfolios with Multi-Objective Optimization

    Linear Programming in Python using PuLP – Part 3: Optimizing Investment Portfolios with Multi-Objective Optimization

    In this article, we used the Pulp library in Python to solve a linear programming problem to find the optimal investment portfolio. We defined variables, added constraints, defined objectives, and solved the problem to find the optimal solution that balances the trade-off between maximizing returns and minimizing risk. The code was concise and easy to…

  • Linear Programming in Python using Pulp – Part 2

    Linear Programming in Python using Pulp – Part 2

    In this article, we delve deeper into linear programming and explore how to solve a multi-objective optimization problem using the Pulp library in Python. We present a problem in which a nutritionist must find the optimal meal plan for a patient suffering from anemia, balancing the intake of Vitamin B12 and fat. We demonstrate how…

  • Linear Programming in Python using PuLP – Part 1

    Linear Programming in Python using PuLP – Part 1

    Linear programming is an optimization technique used to find the best outcomes for a given problem. This technique relies on a set of constructs which are all expressed using a system of linear equations. It is important to understand that you should be able to express your objective as a linear equation dependent on an…

  • How To: Setup Tensorflow With GPU Support using Docker

    How To: Setup Tensorflow With GPU Support using Docker

    Previously I published a guide for setting up tensorflow in an anconda environment with GPU support. A lot of people liked it and I have been working with this environment myself for more than a year now. I am happy with the results however the process is a bit involved and requires quite a bit…

  • How To: Setup Tensorflow With GPU Support in Windows 11

    How To: Setup Tensorflow With GPU Support in Windows 11

    It's been just 2 days since Windows 11 came out and I am already setting up my system for the ultimate machine learning environment. Today we are going to setup a new anaconda environment with tensorflow 2.5 with GPU support using NVIDIA CUDA 11.4 and CUDNN 8.2.4 along with Python 3.8. This is going to…

  • Tools of The Trade – II

    Tools of The Trade – II

    In continuation of my previous post today I will talk about the website tanooja.com. I did this project on request of my wife because she wanted to pursue blogging and didn't want to go through the ordeal needed to write, publish and manage SEO using most of the prominent blogging platforms like WordPress, Joomla, Drupal…

  • Tools of The Trade – I

    Tools of The Trade – I

    In this post I will share a few tools and technologies that I am using to run a couple of blazing fast websites using latest modern tools and technologies. The caveat here is that I don't pay any infrastructure/hosting costs for any of these websites and they can scale infinitely in terms of supported users…

  • Building Lizzie – IV

    Building Lizzie – IV

    Another post about Lizzie. I started off with a Raspberry Pi 3 to build a personal assistant for my car and I have come a long way both in terms of the concept and the functionality. Most importantly I have formalized the application flow and also extended the scope from one device to almost all…

  • OBD-II with Raspberry Pi3

    OBD-II with Raspberry Pi3

    I am writing this article in response to a question posted on my YouTube channel. Here I would be talking about communicating to an OBD-II device (ELM327 chip with Bluetooth) hooked into your car’s OBD-II port. The OS I am using is Windows 10 IoT core. This information is important because it makes a difference…

  • Building Lizzie – III

    Building Lizzie – III

    As mentioned in previous article today I would be talking about OBD-II integration in Lizzie using a Bluetooth serial communication with an ELM327 adapter that fits on a OBD-II port in your car. OBD stands for On Board Diagnostics which is connected to the ECU (Engine Control Unit) and provides a ton of information (both…

  • Building Lizzie – II

    Building Lizzie – II

    In the previous post I described my experiments around building an intelligent artificial personal assistant – Lizzie. The pseudo intelligent agents available today around us (Siri, Cortana or Google Next) are all great feats of engineering given the fact that they reside on small devices like mobile phones and are able to do powerful things…

  • Building Lizzie – I

    Building Lizzie – I

    Recently I have been busy building a personal assistant that I would be fitting in my car. Currently I am in experimentation mode and I am experimenting with speech capabilities. I would start with a description of my journey so far. First let me show off a little bit with these videos that I created…

%d bloggers like this: