| Start |
|---|
| Func and Action Func provides a holder for parameterised anonymous functions. The leading types are the inputs and the last type is always the return value. Action objects are like void methods so they only have an input type. No result is placed on the evaluation stack. |
| Avoid Null References C# developers get a lot of null reference exceptions to deal with. F# developers don't because they have the Option type. An Option<> type (some prefer Maybe<> as a name) provides a Some and a None return type. It makes it explicit that a method may be about to return a null record. For instance, you can't read the following and know if you will have to deal with a null value. If you do know about the possible null you can introduce some boilerplate code to deal with it. What if we have an Option<> returned instead? The code now makes it explicit that we may have a None record returned and the boilerplate code to check for Some or None is required: The following method shows how to return an Option<> Here is a minimal implementation of Option<>. To demonstrate the above avoidNull.csx (opens new window) can be run with the C# REPL. As stated, this is a minimal implementation. A search for "Maybe" NuGet packages (opens new window) will turn up a number of good libraries. |
| Higher-Order Functions A higher-order function is one that takes another function as an argument or returns a function (or both). This is commonly done with lambdas, for example when passing a predicate to a LINQ Where clause: The Where() clause could receive many different predicates which gives it considerable flexibility. Passing a method into another method is also seen when implementing the Strategy design pattern. For example, various sorting methods could be chosen from and passed into a Sort method on an object depending on the requirements at run-time. |
| Immutability Immutability is common in functional programming and rare in object oriented programming. Create, for example, an address type with mutable state: Any piece of code could alter any property in the above object. Now create the immutable address type: Bear in mind that having read-only collections does not respect immutability. For example, is not immutable, as the user of the object can alter the collection (add or remove elements from it). In order to make it immutable, one has either to use an interface like IEnumerable, which does not expose methods to add, or to make it a ReadOnlyCollection. With the immutable object we have the following benefits:
|
| Immutable collections The Creating and adding itemsCreating using the builderCertain immutable collections have a Creating from an existing IEnumerableList of all immutable collection types:
|
Read Article
https://develop.horje.com/learn/1434/reference