Mostrando entradas con la etiqueta Chapter 1. Mostrar todas las entradas
Mostrando entradas con la etiqueta Chapter 1. Mostrar todas las entradas

domingo, 20 de marzo de 2016

LINQ Recipe No. 1-5: How to Install LINQPad?

Contents

1. Introduction
2. Key Words
3. Problem
4. Solution
5. Discussion
6. Practice: Download and Install LINQPad
6.1 Download
6.2 Installation
6.3 Execution
7. Conclusions
8. Literature & Links

1. Introduction

In this new LINQ recipe, LINQPad will be installed. LINQPad is a useful and powerful tool designed to write C#, VB.NET, F# code snippets. In the rest of these LINQ recipes many code snippets will require a validation: the code must reflect a real world model specification. Although Visual Studio can be used to test our recipes, LINQPad features many of the relevant Microsoft .NET programming characteristics necessary for functional programming practicing.

2. Key Words

  • .NET
  • LINQ
  • LINQPad
  • Microsoft .NET Programming

3. Problem

How to install LINQPad?

4. Solution

In order to validate and use our LINQ recipes, we need to download and install LINQPad in our development environment system.

5. Discussion

LINQPad is considered an scratchpad for writing C#, F# and Visual Basic .NET code. It is also designed to interact with many of the available SQL databases. What makes this tool special is if we want to write C# code, an IDE is not required: Visual Studio can be used but LINQPad lets us write code and interact with it in a more comfortable and interactive way.


As has been mentioned in a Wikipedia article ("LINQPad", 2016), LINQPad can support the following dialects:

  • LINQ to XML
  • LINQ to SQL
  • LINQ to objects, and 
  • Entity Framework

6. Practice: Download and Install LINQPad

6.1 Download

LINQPad can be download from this website: https://www.linqpad.net/
LINQPad's website
Illustration 1. LINQPad's website.
Once we open the LINQPad's website, we need to click over the 'Download LINQPad' button.

A new page is loaded: here we click on 'Download LINQPad 5*':
Downloading LINQPad 5
Illustration 2. Downloading LINQPad 5.

6.2 Installation

Now we must execute the recent downloaded file. The installation is easy and intuitive: we just only need to follow the wizard and click Next..., Next.
LINQPad installation wizard
Illustration 3. LINQPad installation wizard.

[Note: It is possible that the system does not meet Microsoft .NET Framework 4.6 requirement, so this must be install before LINQPad can be used.]

6.3 Execution

In Illustration 4 we see the LINQPad's welcome screen. This is the start point to write and run code.
C# Expression in LINQPad
Illustration 4. C# Expression in LINQPad.

7. Conclusions

LINQPad will be used to write LINQ in future recipes. As we have learned in this recipe, this tool offers the fundamentals program elements to write functional programming code with a well designed environment. This environment is suited to interact with C#, F# and Visual Basic .NET code, and SQL databases.

The next recipe will teach us how to make basic math and statistics in LINQ: how to find the dot product of two vectors.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
LINQPad (2016, March 20). Retrieved from: https://en.wikipedia.org/wiki/LINQPad
LINQPad - The .NET Programmer's Playground (2016, March 20). Retrieved from: http://www.linqpad.net/


V

sábado, 19 de marzo de 2016

LINQ Recipe No. 1-4: What are the Benefits of Functional Programming?

Contents

1. Introduction
2. Key Words
3. Problem
4. Solution
5. Discussion
6. Conclusions
7. Literature & Links

1. Introduction

In this fourth LINQ recipe we will be familiarized with the benefits of functional programming paradigm. The comprehension and usage of these benefits -composability, lazy evaluation, immutability, parallelizability, and declarativity-, will allows to take advantage of functional programming, and write robust, stable, and powerful code. For this recipe, a basic explanation of these benefits will be presented to understand their fundamentals.

2. Key Words

  • .NET
  • Composability
  • Functional programming
  • Immutability
  • Lazy evaluation
  • LINQ
  • Parallelizability

3. Problem

What are the benefits of functional programming paradigm?

4. Solution

The benefits of this programming paradigm includes:
  • Composability
  • Lazy evaluation
  • Inmmutability
  • Parallelizability
  • Declarativity

5. Discussion

5.1 Composability

With composability, the programmer is able to partition a problem solution in a functional granular approach. This means that a set of methods or code blocks perform a single and well defined task. Throughout this principle, the creation of solutions for complex problems will be easier: "it's the only way to combat complexity." (Mukherjee, 2014). The solution code will be more maintainable and easy to refactor: thanks to the divide and rule principle.

5.2 Lazy evaluation

Lazy evaluation -or deferred execution-, is a sophisticated mechanism for recovering data using filters. These filters recover data only when some particular condition is met. Suppose you have a big collection of objects stored in a remote data storage and you decide to filter that collection according to some condition: only those objects which fulfill the condition will be shown when they are requested. With this in mind, the program performance is better compared to an imperative solution (where each of operations for recovering data will be evaluated).

5.3 Immutability

Immutability lets us write code free of side of effects. However, the functional programming paradigms does not guarantee us that our code implementation won't have side effects in its implementation. Instead, a set of good practices for functional programming exist to attack undesirable side effects in our program solutions.

According to Mukherjee (2014), side effects such as shared variables could make a program unstable and unreliable: multiple objects could try to access a certain memory area -a variable- at the same time, so this limits the program speed to the variable response time. A more reliable and feasible approach is start a thread with its set of states: this avoids waiting for access to shared variables.

5.4 Parallelizability

LINQ lets us use program elements such us AsParallel() ("ParallelEnumerable.AsParallel Method", 2016) and AsOrdered() ("ParallelEnumerable.AsOrdered Method", 2016) to parallelize code. Given that the code is free of side effects (immutability property) by design, most functional programs are easy to parallize.

[Note: In future LINQ recipes we will explore how the previous mentioned methods are used in C# code.]

5.5 Declarativity

Declarative programming lets us write code into a single line: this is done by using LINQ operators. The declarative code is very expressive and its readability can help us easy understand the purpose of an algorithm.

6. Conclusions

In this recipe we have learned what are the benefits of using functional programming in very general terms. In future recipes we will get deeper in each of those benefits with an extended explanation and comprehension, even with a lot examples to reinforce our understanding.

7. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
ParallelEnumerable.AsParallel Method (System.Linq) (2015, March 17). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.parallelenumerable.asparallel%28VS.100%29.aspx?f=255&MSPPError=-2147217396
ParallelEnumerable.AsOrdered(TSource) Method (ParallelQuery(TSource)) (System.Linq) (2015, March 17). Retrieved from:
https://msdn.microsoft.com/library/dd413357(v=vs.100).aspx


V

sábado, 5 de marzo de 2016

LINQ Recipe No. 1-3: How to Use the Various Types of Functions

Contents

1. Introduction
2. Keywords
3. Problem
4. Solution
5. Discussion
5.1 Generator functions
5.2 Statistical functions
5.3 Projector functions
5.4 Filter functions
6. Practice: Types of Functions - Examples
7. Conclusions
8. Literature & Links

1. Introduction

In this new LINQ recipe many new concepts about the different types of functions will be presented. We will study and practice how to use the kinds functions like: generator, statistical, projector, and filter. As we will see, these kinds of functions will allow us to manipulate data in more broadly way than the basic ones (those presented in recipes 1-1 and 1-2). In the practice section a series of examples will be explained to reinforce the comprehension for further recipes of this interesting topic: functional programming with LINQ in Microsoft .NET applications.

2. Keywords

  • .NET
  • Data
  • Generator
  • Filter
  • Function
  • LINQ
  • Microsoft
  • Projector

3. Problem

The programmer needs to learn which kinds of functions exist in functional programming and how they work to manipulate data in a more sophisticated way.

4. Solution

In functional programming there exist up to four categories for functions:
  • Generators
  • Statistical
  • Projectors
  • Filters

5. Discussion

The .NET Framework offers to the programmer, in the functional programming context, four types of functions.
Types of Functions
illustration 1. Types of Functions (Mukherjee, 2014).

5.1 Generator functions

This kind of function lets the programmer to generate values out of nothing (Mukherjee, 2014). They can be represented using this equation:

() => T[]

Where T represents the output data type for the function. In the general sense, this type of function could be viewed like a method without parameters. The .NET Framework comes with many built-in generator functions; among them we have:
  • Enumerable.Range(): generates a sequence of integral numbers between an specified range. ("Enumerable.Range Method", 2016).

5.2 Statistical functions

It's possible to generate statistics from a collection of elements. This is done by using the built-in statistical functions
  • Any(): this function determines whether one or more elements satisfy some condition. Its return data type is bool. ("Enumerable.Any(TSource) Method", 2016)
  • Count():  this function function returns the number of elements in a collection. ("Enumerable.Count(TSource)", 2016)
  • Single(): this returns a single (one) element from a collection. ("Enumerable.Single (Method)", 2016)
  • Sum(): calculates the addition of a collection of numerical elements. ("Enumerable.Sum (Method)", 2016)
Many of the above methods has multiple overloaded versions suited for different requirements.

On the other hand, the general syntax is

T[] => Boolean
T[] => Number

T[] corresponds to a collection of elements (more commonly integer values) and the return type is an primitive type like Boolean or Number.

5.3 Projector functions

The projector functions is suitable to process -project- a collection elements and return a collection of elements; i.e.:

T[] => U[]

For example, if we have a collection with city names and if we want to create -project- a collection with number of letters for each city name, then we must use a projector function to perform this process. The general equation for this example is 

String[] => Integer[]

Some of the available functions are: 
  • Select(): projects each collection element from one representation to a new one. ("Enumerable.Select(TSource, TResult)", 2016)
  • SelectMany(): project each collection element to an IEnumerable<T> data type. 

5.4 Filter functions

With these kind of functions the programmer can filter out the elements of a specified collection. Examples of these functions can be: 
  • First()
  • Last()
  • Where()
According to Mukjerhee (2014) a filter function can be represented using either of these two equations:
  • T[] => U[]: the filter function returns a list of elements (a collection).
  • T[] => T: this function returns a single element according to condition or predicate.

6. Practice: Types of functions - Examples

Now we can proceed to elaborate some code example to reinforce our comprehension about the different kinds of functions.


In line 14 we generate five integers -from 1 to 5-. With the line 24 we enlist 5 Microsoft products, then with the functional method Count we count the number of elements in the sequence: 5.


Now, we proceed with the use of projector functions. In particular, in the line 31, numbers from 1 to 5 are cubed. Finally with the code in the line 41 we select the first element from the string array msProducts.

Code compilation:

csc /t:exe TypeFunctionsExamples.cs

Assembly execution:

.\TypeFunctionsExamples.exe

Online assembly execution (ideone.com): http://ideone.com/RJpfw5

Local assembly execution:
Assembly TypeFunctionsExamples.exe execution
Illustration 2. Assembly TypeFunctionsExamples.exe execution.

7. Conclusions

We have learned to distinguish the different kinds of functions: generators, statistical, projector, and filters. As we have seen all of these functions can be glued together to manipulate or transform data from different sources. In the example code presented, we have got a first sight to the functional programming methods available in the .NET Framework; in future recipes or articles we will go deeper.

In the next recipe we are going to understand the benefits of functional programming.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
Enumerable.Range Method (System.Linq) (2016, March 4). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.100).aspx
Enumerable.Any(TSource) (Method) (IEnumerable(TSource), Func(TSource, Boolean)) (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/library/bb534972(v=vs.100).aspx
Enumerable.Count(TSource) (Method) (IEnumerable(TSource)) (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/library/bb338038(v=vs.100).aspx
Enumerable.Single (Method) (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/es-es/library/system.linq.enumerable.single(v=vs.110).aspx
Enumerable.Sum Method (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.enumerable.sum(v=vs.110).aspx
Enumerable.Select(TSource, TResult) Method (IEnumerable(TSource), Func(TSource, TResult)) (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/library/bb548891(v=vs.100).aspx
Enumerable.SelectMany(TSource, TResult) Method (IEnumerable(TSource), Func(TSource, IEnumerable(TResult))) (System.Linq) (2016, March 5). Retrieved from: https://msdn.microsoft.com/en-us/library/bb534336(v=vs.110).aspx


V

jueves, 25 de febrero de 2016

LINQ Recipe No. 1-2: How to Use the Func Delegate to Represent Functions

Contents

1. Introduction
2. Keywords
3. Problem
4. Solution
5. Discussion
6. Practice: Writing Functional Methods With Func Data Type
7. Conclusions
8. Literature & Links

1. Introduction

In this recipe the programmer will learn how to write functions using the Func<> delegate. As it will be shown, this delegate is the most versatile and useful mechanism to implement simple and compound functions. Also, the programmer will have the opportunity to grasp the theoretical and practical foundations of functional programming using the C# programming language.

2. Keywords

  • C#
  • Compound function
  • Data type
  • Delegate
  • Functional programming
  • Simple function

3. Problem

In the previous recipe we learned the purpose and the mathematical foundations for functional programming -LINQ Recipe No. 1-1: Introduction to LINQ Programming Model - Functional Programming-. We also developed some basic, but instructive, examples about simple and composite functions. Now what we need to do is represent that functions using the C#'s built-in programming elements.

4. Solution

The C# programming language offers to the programmer the Func delegate to build functional methods; using a very expressive syntax for complex functions.

5. Discussion

5.1 Delegates

The delegate data type is designed to specify an abstract method definition. For example if we define:

public delegate int ExecuteCalculation(int x, int y);

Then, any method which matches ExecuteCalculation's signature (parameters and return type) can be assigned to an instance of this delegate.

Given the method Add with this signature and return type 

public int Add(int x, int y)
{
return (x + y);
}

we then instantiate the ExecuteCalculation delegate 

ExecuteCalculation delegateExecuteCalculation;
delegateExCalculation = Add;

and finally, an intermediated call to the Add method is perfomed 

Console.WriteLine("Sum of 2 + 3 = {0}", delegateExecuteCalculation(2, 3));

Func built-in delegate is abstract because it receives any method signature which matches with its own signature:

public int Subtraction(int x, int y)
{
    return (x - y);
}

delegateExecuteCalculation = Subtraction;
Console.WriteLine("Sub of 2 - 3 = {0}", delegateExCalculation(2, 3));

5.2 Func C# class

The Func class represents built-in delegates to create functional methods. C# has up to 16 versions for this class. Each of them has a different number of generic parameters. This is because the programmer could be required to code a functional method with different set of parameters.

In the System namespace we can find all of the built-in Func delegates. They are 
  • Func(T, TResult)
  • Func(T1, T2, TResult)
  • Func(T1, T2, T3, TResult)
  • ...
  • Func(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult)
Why do we need all of these Func versions? Because this avoid the explicit and manual declaration for delegates. For instance, the ExecuteCalculation delegate (declared in the previous section) can simply declared as:

Func<int, int, int, int> delegateExecuteCalculation;

and then assigned any of the previous sample methods:

delegateExecuteCalculation = Add;

But we can also write the delegate's implementation as follows:

Func<int, int, int, int> delegateExecuteCalculation = (x, y) => x + y;

6. Practice: Writing Functional Methods with Func Data Type

In the previous recipe -LINQ Recipe No. 1-1: Introduction to LINQ Programming Model - Functional Programming- we created the mathematical functions:

f(x) = x + 1
g(x) = x + 2

With the Func data type we simply define them as 

Func<int, int> f = x => x + 1;
Func<int, int> g = x => x + 2;

Therefore the mathematical compound function 

f(g(x))

is written in C# code as 

Funcint, int>, Func<int, int>, int, int> fog = (f1, g1, x) => f1.Invoke(g1.Invoke(x));

Unifying all of these examples, we write this complete C# program:



On line 10 we define the f mathematical function using Func<int, int>: input parameter as int, and int as return data type. This is also apply for the g mathematical function (line 11).


On the other hand, with line 14 the compound mathematical function f(g(x)) is specified with this code:
  • Func<int, int>: receives a Func type; which can be the f or g function. In this case f.
  • Func<int, int>: receives a Func type; which can be the f or g function. In this case g.
  • int: the input parameter for the inner function.
  • int: the output data type.
Compilation:

csc /t:exe FunctionalMethods.cs

Assembly execution:

.\FunctionalMethods.exe

Online execution (ideone.com): http://ideone.com/ztvRjz

Local execution:
FunctionalMethods.exe assembly execution
Illustration 1. FunctionalMethods.exe assembly execution.

7. Conclusions

In this recipe we have learned how to use built-in delegates to create functional methods with a very expressive syntax. Instead of writing our own delegates we can take advantage with the built-in ones: we must remember that there are up to 16 different versions of the Func type. With this in mind, we can make our code more expressive and manageable.

In the next recipe, we are going to understand types of functions.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
C# Func Type (2016, febrero 25). Retrieved from: http://www.dotnetperls.com/func
Using Delegates (C# Programming Guide) (2016, febrero 25). Retrieved from: https://msdn.microsoft.com/en-us/library/ms173172(v=vs.110).aspx


V