Define symbolic operators with F#

This post describes how we can define a custom operator with F#. Defining a new operator in F# is very straightforward. For instance, by using the following code, we can define “!” as an operator to compute factorial of an integer.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 let rec (!) n = match n with | 1 -> (1) | n -> n*(n-1)
view raw sym_op.fs hosted with ❤ by GitHub

Running the following command in the interactive F# console computes the factorial for 10.

```> !10;;
val it : int = 3628800
>```

A symbolic operator can use any sequence of the following characters: ` ! % & * + - . / ? @ ^ |~`. Note that, “:” can also be used in the character sequence of symbolic operation if and only if, it is not the first character in the operator.

Following is an example of modulo operator defined using F#:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 let rec (|%|) a n = match a, n with |_ when a < n -> a |_ when a>=n -> (|%|) (a-n) n //Resulting signature: val ( |%| ) : int -> int -> int
view raw modulo.fs hosted with ❤ by GitHub

Following outputs shows how to use it from F# interactive shell.

```> 23 |%| 3;;
val it : int = 2
> 3 |%| 3;;
val it : int = 0
>```

F# | Length of a List

The code snippets listed below defines a function to compute the length of a give list using F#. Note that these functions are also called polymorphic function, as they work with any type of list (as shown in the output).

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 // naive implementation let rec length list = match list with | [] -> 0 | _::tail -> 1 + computeLength tail
view raw gistfile1.fs hosted with ❤ by GitHub

A `tail recursive implementation `is outlined next.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 // Tail recursive computation of List's length let length list = // Auxiliary function to compute length // It store intermediate result in acc. let rec lengthAux acc list = match list with | [] -> acc | _::tail -> lengthAux (acc+1) tail lengthAux 0 list // invoking lengthAux with acc = 0
view raw gistfile1.fs hosted with ❤ by GitHub

Following is a more succinct implementation using `List.Fold`.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 let length list = List.fold (fun acc _ -> acc+1) 0 list
view raw length.fs hosted with ❤ by GitHub

Output:

```> length [];;
val it : int = 0
> length [1;2;3;4];;
val it : int = 4
> length ['a';'b'];;
val it : int = 2
```

Comparison Of Different Channels In WCF

Few months back, we did some measurement of different WCF channel to get the precise idea about the performance in the different channel stack.

Following is the definition of the environment:

1. WCF service and client is hosted in the same Windows 2003 Server.
2. 537 Users exist in the system.
3. WCF service is hosted in Windows Service.
4. System.Diagnostics.Stopwatch is used to measure time elapsed in Millisecond.
5. Two user credentials are used: one domain user & the local system account on which the server was running.

Primary goal was to measure the time required for each GetUsers() call( in milliseconds) for combination Binding and InstanceContextMode. That’s why, we took average of 10 Test Run (in different scenario) for each combination where in each Test Run, we call the GetUsers() 100×10 Times . Here comes the result:

• From the graph above, it’s quite obvious that NetTcpBinding(PerSession) is the best performer, which is quite expected as per its channel behavior. Interestingly, if we look at the WsHttpBinding(PerSession), it is taking more time than session unaware BasicHttpBinding. There is a similarity in the trend of BasicHttpBinding (PerCall by default) , WsHttpBinding(PerCall) and NetTcpBinding(PerCall) in the first TestRun; as the first GetUsers() is setting up the whole channel stack, its taking more time than its usual time. On the other hand, WsHttpBinding(PerSession), and NetTcpBinding(PerSession) are more consistent in every Test Run because of the reusability of the Session. We measure that 15ms is the time taken on average to create a new Application specific session in our system.

• Following is the Chart of the average time taken per request in milliseconds for each combination:

I would recommend you to visit Wcf Binding Comparision List and Supported Features (Reference)
for a quick comparison of different channel in terms of Transport Protocol, Message Encoding, and Message Versioning and so on.

Hope it helps to you to choose the right channel stack for your application.

Cheers! J

Inside Static Constructor (.cctor)

The primary objective of using a static constructor (also known as, type constructor, class constructor or .cctor) is to initialize static members of a type, or performing some operations, which seems to be preconditions for performing any operation on a particular type, or an instance of the type. Furthermore, it is useful in creating wrapper of unmanaged classes, when the constructor can call `LoadLibrary` method.

It can only be defined as a static member of a type as follows:

```public class StaticConstructorDemo{
static ILogger _logger;
static StaticConstructorDemo(){
// ... initial setup
_logger = new TextLogger();
}
}
```

Few notable facts about static or type constructor:

[1] Type constructor will be called just once after its being loaded in the application domain. Timing when it will be called is completely depends on CLR.  But it will surely be called before instantiation of any object from the type or before any invocation of a static method. So, it might be the right place for executing those codes that are needed to be executed just once and before any methods (static/instance) of the class invoked. There is not specific order mentioned for execution of .cctor in inheritance/association scenario. Order on which the .cctor will get executed completely depends on the CLR.

[2] Type constructor is thread safe. So, only one thread in the app-domain can run this constructor, as CLR ensures the thread safety of .cctor. If multiple thread try to access a .cctor, only one thread will eventually be successful to get a mutually exclusive lock on the type constructor while other thread will be blocked. After the current thread complete its execution of .cctor, other thread will wake up and monitor that .cctor has been executed before. Hence, they will just return without executing the .cctor.

[3] Any access modifier before the type constructor is not allowed, otherwise it results in following compile time error: “access modifiers are not allowed on static constructors“.

[4] It does not accept any arguments, and can be applied to both value and reference types.

Exception Handling

Consider following code–

```public class StaticConstructorExceptionDemo{
public static int Result = 0;
static StaticConstructorExceptionDemo{
int test = 0;
Result = 100/test; // throws DivideByZeroException
}
}
```

When static property `Result` is accessed for the first time (after being loaded in the current context), we expect a `DivideByZeroException` to be thrown from `StaticConstructorExceptionDemo()`. In contrast, it gets TypeInitializationException.

However, it is worth noticing that the `_innerException` is actually pointing to an instance of `DivideByZeroException`.

Therefore, please underscore the following important points while handling exceptions related to type constructor.

[1] We should not throw exception from the type constructor unless we come to a conclusion that the type is unusable for further usage. Due to any unhandled exception, type becomes completely unusable in the currently loaded appdomain (context).

[2] In case of any exception inside type constructor, we should expect an instance of `TypeInitializationException`, which refer to the original exception as its inner-exception.

Performance Optimization

By utilizing static members, we get motivated to implement singleton pattern in the following manner–

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 public class FileSystemLogger:ILogger { public static FileSystemLogger Instance = new FileSystemLogger(); // ILogger Implementation }
view raw gistfile1.cs hosted with ❤ by GitHub

Alternatively, we can implement it by utilizing by introducing a type constructor:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 public class FileSystemLoggerWithCCTOR:ILogger{ public static FileSystemLoggerWithCCTOR Instance; static FileSystemLoggerWithCCTOR(){ Instance = new FileSystemLoggerWithCCTOR(); } }
view raw gistfile1.cs hosted with ❤ by GitHub

Although both class functionally looks quite similar, there is a subtle difference between them. If we fire up ILDASM, we can see an extra attribute added in `FileSystemLogger`, which is missing in `FileSystemLoggerWithCCTOR`— “beforefieldinit”.

According to MSDN, it “specifies that calling static methods of the type does not force the system to initialize the type“.

As we can see, in first class `FileSystemLogger`, CLI mark the class with `beforefieldint` that means that calling the methods of `FileSystemLogger`does not enforce static field initialization. The reason CLI does this: as per CLI specification, it is expensive to ensure that static fields are initialized before any of the static method get called. When multiple application domain comes into account, it become more expensive.

However, CLI enforce static field initialization when any of the static field is accessed. On the other hand, `FileSystemLoggerWithCCTOR` has a static constructor which results in an assurance from the CLI that static constructor will get called before any static member would be invoked, which in turn, initializes all the static members of the class. However, that means, performance optimization using beforefieldinit is no longer possible with this implementation.

Conclusion

We have to use type constructor with care. We should consider not to use type constructors as long as we can, to enable performance optimization by CLI via beforeFieldInit.

Hope it helps. Thanks for visiting the blog!

Revisions

[R-2: 30-03-2013] Minor formatting changes.
[R-1: 29-03-2013] Updated formatting to make this post more consistent with current CSS.

Code Snippet: Adding a File to .net Resource

Last few days, I was thinking to jot down all the code snippet that I used very frequently.  Here comes the first one –

Today’s post will be covering a simple aspect of every .net project where one has to add files in Resource and get it from there for further processing.

To Add & Get the file from the resource , we have to –

1. Select the file that we want to put in the resource –

And from the property window, set the Build Action = “Embedded Resource”.

2. To get file from the resource, we have to write following few lines of codes –

In this code snippet , as we can see , I am getting the resource from the Assembly Menifest and returning it as XmlReader to the caller as –

And we are done.