muhbaasu / fx-sharp

Fx# - Functional extensions for C#.
http://muhbaasu.github.io/fx-sharp/
Apache License 2.0
2 stars 0 forks source link

fx-sharp

The name fx-sharp stands for functional sharp. Goal of the project is to bring advanced functional concepts, such as the Maybe(Option) type or the Either type, to C#.

Maybe

Key benefits

Chaining of operations which may fail

This example demonstrates a case, where multiple sequential operations are dependent on the result of a prior operation.

Previously

Caller caller = null;
var name = TelephoneDirectory.LookUpName("+49394965006"); // LookUpName returns null when not found
if (name != null) {
  var photo = SocialNetwork.LookUpPhoto(name); // LookUpPhoto returns null when not found
  if (phote != null) {
    caller = new Caller(name, photo);
  }
}

With fx-sharp

var caller = from name in TelephoneDirectory.LookUpName("+49394965006") // LookUpName returns Maybe[string]
             from photo in SocialNetwork.LookUpPhoto(name)              // LookUpPhoto returns Maybe[Image]
             select new Caller(name, photo);

Handle failure and success

"Pattern match" the result of a method that returns a Maybe.

Previously

var name = TelephoneDirectory.LookUpName("+49394965006") // LookUpName returns null when not found
if (name != null} {
  view.DisplayName(name.ToUpper())
} else {
  view.DisplayName("Unknown caller"))
}

With fx-sharp

TelephoneDirectory
    .LookUpName("+49394965006") // LookUpName returns Maybe[string]
    .Match_(
        just: name => view.DisplayName(name.ToUpper()),
        nothing: () => view.DisplayName("Unknown caller"));

Default Value

Provide a default value, if a function returns Nothing.

Previously

var name = TelephoneDirectory.LookUpName("+49394965006") ?? "John Doe"; // LookUpName returns null

With fx-sharp

var name = TelephoneDirectory
            .LookUpName("+49394965006") // LookUpName returns Maybe[string]
            .GetOrElse("John Doe");