Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning F# Functional Data Structures and Algorithms

You're reading from   Learning F# Functional Data Structures and Algorithms Get started with F# and explore functional programming paradigm with data structures and algorithms

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher Packt
ISBN-13 9781783558476
Length 206 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Adnan Masood Adnan Masood
Author Profile Icon Adnan Masood
Adnan Masood
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Embrace the Truth FREE CHAPTER 2. Now Lazily Get Over It, Again 3. What's in the Bag Anyway? 4. Are We There Yet? 5. Let's Stack Up 6. See the Forest for the Trees 7. Jumping the Queue 8. Quick Boost with Graph 9. Sets, Maps, and Vectors of Indirections 10. Where to Go Next? Index

Syntactical similarities and differences

Let's expand upon the preceding example and compare the syntactical differences between F# and C# through another simple example, the sum of a square method. A shorter and elegant looking functional syntax follows:

let square x = x * x
let sumOfSquares n = [1..n] |> List.map square |> List.sum 

Here you see the use of one of F#'s celebrated operators, that is, the |> pipe forward operator. It essentially performs piping operations by passing the results from left the side of the function to the right side, and can be concatenated.

Running this program in F# the interactive console yields the following results for

sumOfSquares 2 

and

sumOfSquares 3 

respectively:

Syntactical similarities and differences

The sum of the squares method in C# looks something like this:

public class SumOfSquares
{
  public static int CalculateSquaresSum(int n)
  {
    var sum = 0;
    for (var i = 1; i <= n; i++)
    {
      sum += Square(i);
    }
    return sum;
  }
  public static int Square(int x)
  {
    return x * x;
  }
}

Again, the C# version is quite verbose and can be made more functional by using LINQ as seen next:

public static int SquaresSum(int n)
{
  return Enumerable.Range(1, n)
  .Select(i => i * i)
  .Sum();
}

This can be further reduced to the following code:

public static int SquaresSum(int n)
{
  return Enumerable.Range(1, n)
  .Sum(i => i * i);
}

In this case, IEnumerable is used along with a Select filter, which sums up the results. Numbers from a sequence are each squared and aggregated into a sum.

Project Euler provides a series of mathematical and programming problems that can be solved using programming languages of your choice. Following is problem #1 from Project Euler:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23 Find the sum of all the multiples of 3 or 5 below 1000.

An F# solution to this problem can be written as follows:

let total = [1..999] |> List.map (fun i -> if i % 5 = 0 || i % 3 = 0 then i else 0) |> List.sum

In this case we operate on 1-999, chain the operator with map to perform a modulus operation, and then sum up the results. An alternate approach is to use a filter that categorizes the results and provides a collection to perform a sum on. This approach can be listed as follows:

let total = [1..999] |> List.filter (fun i -> i % 5 = 0 || i % 3 = 0) |> List.sum

The solution in C# following the same algorithm results in a verbose listing as seen here:

public static int CalcSumOfMultiples()
{
  int result = 0;
  for (int i = 1; i < 1000; i++)
  {
    if ((i % 3) == 0 || (i % 5) == 0)
    {
      result += i;
    }
  }
  return result;
}

This C# code can be LINQ'ified to a more terse syntax as follows:

var total = Enumerable.Range(1, 999).Select(x => x % 3 == 0 || x % 5 == 0 ? x : 0).Sum();

Another better way of doing this can be seen in the next code listing:

var total = Enumerable.Range(1, 999).Sum(x => x%3 == 0 || x%5 == 0 ? x : 0);

The F# solutions of Project Euler problems, to further help understand algorithms and data structures can be found at https://github.com/adnanmasood/Euler.Polyglot.

You have been reading a chapter from
Learning F# Functional Data Structures and Algorithms
Published in: Jun 2015
Publisher: Packt
ISBN-13: 9781783558476
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image