concept function in category .net

appears as: function, functions, functions, The function, function, A function, The functions, A function
Concurrency in .NET

This is an excerpt from Manning's book Concurrency in .NET.

FP is about minimizing and controlling side effects, commonly referred to as pure functional programming. FP uses the concept of transformation, where a function creates a copy of a value x and then modifies the copy, leaving the original value x unchanged and free to be used by other parts of the program. It encourages considering whether mutability and side effects are necessary when designing the program. FP allows mutability and side effects, but in a strategic and explicit manner, isolating this area from the rest of the code by utilizing methods to encapsulate them.

A function that takes a filesystem path may throw an error if the directory doesn’t exist or if the running program doesn’t have the required permissions to read from the directory. Another point to consider is that with a function run in parallel using PLINQ, the query execution is deferred until its materialization. Materialization is the term used to specify when a query is executed and produces a result. For this reason, successive materialization of a PLINQ query that contains side effects might generate different results due to the underlying data that might have changed. The result isn’t deterministic. This could happen if a file is deleted from the directory between different calls, and then throws an exception.

Moreover, functions with side effects (also called impure) are hard to test. One possible solution is to create a testing directory with a few text files that cannot change. This approach requires that you know how many words are in these files, and how many times they have been used to verify the correctness of the function. Another solution is to mock the directory and the data contained, which can be even more complex than the previous solution. A better approach exists: remove the side effects and raise the level of abstraction, simplifying the code while decoupling it from external dependencies.

Listing 5.2 Pure functions in C#
public static string AreaCircle(int radius) =>
 Math.Pow(radius, 2) * Math.PI;   #1   

public static int Add(int x, int y) => x + y;   #1  

#1   The output never changes because the functions have no side effects.

Figure 5.3 The fold function reduces a sequence to a single value. The function (f), in this case, is multiplication and takes an initial accumulator with a value of 1. For each iteration in the sequence (5, 7, 9), the function applies the calculation to the current item and accumulator. The result is then used to update the accumulator with the new value.

c05-03.png
Entity Framework 4 in Action

This is an excerpt from Manning's book Entity Framework 4 in Action.

The way you access data is completely unsafe and generic. On the one hand, you have great flexibility, because you can easily write generic code to implement functions that are unaware of the table field names and rely on configuration. On the other hand, you lose type safety. You identify a field specifying its name using a string; if the name isn’t correct, you get an exception only at runtime.

Listing 10.9. Declaring functions and letting them invoke stored procedures
  • It must be marked with the EdmFunction attribute. (The attribute needs two mandatory parameters: the storage schema namespace and the name of the function.)
  • Its body should throw an exception. (This isn’t mandatory, but because the function is only a stub for LINQ to Entities, its code is never really invoked.)
  • The first step is to create the function in the conceptual schema, as shown here.

    Listing 11.4. User-defined function that returns and accepts scalar values
    <Schema ...> <Function Name="GetUDFTotalAmount" ReturnType="Decimal"> <Parameter Name="UnitPrice" Type="Decimal" /> <Parameter Name="Quantity" Type="Int32" /> <Parameter Name="Discount" Type="Decimal" /> <DefiningExpression> (UnitPrice - Discount) * Quantity </DefiningExpression> </Function> </Schema>

    The declaration is straightforward. In the Function node, you declare the function name and return type. Then, you include a Parameter node for each input parameter. Finally, you create a DefiningExpression node, inside which the function code is written using Entity SQL. That’s it for the EDM.

    Next, you have to create the CLR stub method for the function to make it available to LINQ to Entities. That’s done the same way as for a scalar-valued function except that the first parameter of the EdmFunction attribute must contain the namespace of the conceptual schema, not the namespace of the storage one. Of course, the name must be changed too. The final code is shown in the following snippet:

    All of the preceding functions have one thing in common—they return a single instance. Because functions are all about reuse and encapsulation, it would be a pity if you couldn’t return collections too. Fortunately, that’s possible.

    IronPython in Action

    This is an excerpt from Manning's book IronPython in Action.

    Functional programming is an important programming concept. Pure functional programming allows functions to have no side effects; it can be hard to understand, but the basic concepts are straightforward enough. In functional programming languages, Python included, functions are first-class objects. You can pass functions around, and they can be used far from where they’re created.

    Because class and function creation is done at runtime rather than compile time, it’s easy to have functions that create new functions or classes—that is, function and class factories. These make heavy use of closures. Local variables used in the same scope a function is defined in can be used from inside the function. They’re said to have been captured by the function. This is known as lexical scoping.[32]

    As we mentioned earlier, Python supports several different programming techniques. For simple tasks, which there may be many of in a complex program, functions can be more appropriate than making everything a class. Functional programming can make it hard for others to follow your code if it’s overused, but it can also be extremely powerful. With Python, you’re free to mix procedural, functional, and object-oriented programming to your heart’s delight; and, because they all have their place, you probably will. First things first, though—to do this, you need to know the language.

    Functions allow you to break code down into smaller units and make programs more readable. Functions take values as arguments and return values, but they may also be used for their side effects, such as writing to the filesystem or a database.

    Like other aspects of Python, the syntax for functions is straightforward. It’s shown in figure 2.4.

    Figure 2.4. Function definition, body, and return

    A function is created using the def keyword, followed by the function name and an argument list (which can be empty if the function receives no arguments). Because they introduce a new block of code, function definitions are terminated with a colon.

    The function body is the indented block which follows the def. If the interpreter hits a return statement, then it leaves the function and returns the specified value (or None if no value is supplied). If the interpreter reaches the end of the function body without hitting a return statement at all, then None is also returned.

    If the function needs to receive arguments, then a comma-separated list of names is placed between the parentheses that follow the function name. When the function is called, a value must be supplied for every name in the argument list.

    Functions are the bread and butter of procedural and functional programming. In recent years,[13] a paradigm called object-oriented programming has arisen, building on the principles of procedural programming. Object-oriented programming allows you to combine data with functions (called methods) for working on the data. The basic element in object-oriented programming is a programming construct called the class, which we turn to now.

    Listing 6.13. Importing code and function calls for module as script
    if __name__ == '__main__': import clr clr.AddReference("System.Windows.Forms") clr.AddReference("System.Drawing") from System.Drawing import Size from System.Windows.Forms import ( Button, DialogResult, DockStyle, Panel, Form, FormBorderStyle, Padding, TextBox ) [RenameTabDialog and ShowDialog...] if __name__ == '__main__': print ShowDialog("Something", False) print ShowDialog("Something Else", True)
    ASP.NET AJAX in Action

    This is an excerpt from Manning's book ASP.NET AJAX in Action.

    Welcome.htm is pretty minimal and contains some static text welcoming you to the book. You make the asynchronous request with a few more lines of code that you wrap in a function called sendRequest (see listing 1.3).

    A JavaScript object is nothing more than a collection of name and value pairs called properties. Usually, this kind of structure is also called a dictionary or an associative array. JavaScript provides also an array data type, which is a collection of values of different types. A major role in the language is played by functions, which are objects like dictionaries or arrays. Functions are probably the most powerful objects provided by JavaScript; they’re responsible for its great power and flexibility. In the following sections, we’ll do an overview of objects, arrays, and functions, which are the foundations of the JavaScript language.

    When a language treats functions as objects, it’s said to support first-class functions . This means functions can be instantiated, returned by other functions, stored as elements of arrays, assigned to variables, and so on. A function represents a portion of executable code and, at first look, seems similar to a method of an object in a classic object-oriented language such as Java, C#, or VB.NET.

    As an example, here’s the code for a function called add that returns the sum of its arguments:

    function add(a, b) {
        return a + b;
    }

    Because JavaScript is a loosely typed language, you don’t need to specify the type of the arguments or the type of the returned value (if any). All the information about types is inferred at runtime. As a consequence, if the arguments a and b passed to the add function are numbers, the returned value is their sum. If, on the other hand, a and b are strings, the result is the concatenation of the two strings. If the arguments are of different types, strange things may happen, and an error may be raised at runtime. In chapter 13, we’ll discuss a technique called parameter validation, which the Microsoft Ajax Library uses to check that the arguments passed to a function are of the expected types.

    As shown in this example, you can declare a function without specifying a name. A function with no name is called an anonymous function. Interestingly, assigning an anonymous function to a property lets you invoke it through the property itself:

    Note that this code treats the add and multiply properties as if they were the names of the functions they hold. Accessing a property that holds a function is similar to invoking a method of an object. For this reason, a JavaScript function stored in a property of an object is called a method.

    Let’s continue our discussion of JavaScript functions by introducing two important topics. The first concerns the scope of a function: the context that you can access inside it. The second is another powerful characteristic of functions: the ability to bind them to an environment.