First look at F#

F# first example: simple math library.

namespace MathModule
open System

type Number(a :double) =
    let number = a

    member x.Add(b) =
        Number(a + b)

    member x.Subtract(b) =
        Number(a - b)

    member x.Multiply(b) =
        Number(a * b)

    member x.Divide(b) =
        Number(a / b)

    member x.Sqrt() =
        Number(Math.Sqrt(a))

    member x.Square() =
        Number(a * a)

    member x.Result() = a

Okay, let’s look at the example. We define statements to create new namespace MathModule (#1) and to import System namespace (#2). Then we define new type Number (#4). Number type has a simple object constructor which will be used to initialization of our immutable object (#5). Finally, the maths logic is expressed by the type members (#7-#25). Now we can use F# class library in our C# console application.

using System;
using MathModule;

class TestApp
{
    static void Main()
    {
        var res = new Number(3) // 3
            .Multiply(2)        // 3 * 2 = 6
            .Subtract(2)        // 6 - 2 = 4
            .Square()           // 4 * 4 = 16
            .Result();

        Console.WriteLine(res);
    }
}
// *******
// Output:
// 16
// *******

Okay, lets try to write the same code in C#.

using System;

namespace MathLibrary.CSharp
{
    public class Number
    {
        private readonly double _a;

        public Number(double a)
        {
            this._a = a;
        }

        public Number Add(double b)
        {
            return new Number(this._a + b);
        }

        public Number Subtract(double b)
        {
            return new Number(this._a - b);
        }

        public Number Multiply(double b)
        {
            return new Number(this._a * b);
        }

        public Number Divide(double b)
        {
            return new Number(this._a / b);
        }

        public Number Sqrt()
        {
            return new Number(Math.Sqrt(this._a));
        }

        public Number Square()
        {
            return new Number(this._a * this._a);
        }

        public double Result()
        {
            return this._a;
        }
    }
}

A little more code to type … Of course semantic part is the same 😉

Advertisements

One thought on “First look at F#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s