FSharp: Using the Pipe Operartor to Chain Methods

This is a real quick and simple thing, so uh yeah… One of the things I detest in F# is having to use the “normal” method chaining built into C#. FOr instance with the StringBuilder class:

open System.Text

let something =
    StringBuilder()
      .Append("hi")
      .Append("there")
      .Append("!")
      .ToString()

Now for C# that is acceptable.. but not for F# when the |> operator is involved. I want this:

let something =
  StringBuilder()
    |> Append "Hi" 
    |> Append "There"
    |> Append "!" 
    |> ToString()

Which is actually a lot easier than it might seem. When using the |> the next method has to take in the last method’s result. As long as the last parameter of the method matches up with the result of the last, you’re gold. This will NOT work:

let something =
  StringBuilder()
    |> Append "Hi" 

There’s no StringBuilder to be used for that Append method, so it breaks. Remember, the last parameter of the next method has to be the same as the preceding result. So…:

  let append (text: string) (builder : StringBuilder) =
    builder.Append(text)

  let toString (builder : StringBuilder) =
    builder.ToString()

As you can see, the appendBuiler method has a signature of StringBuilder -> string -> StringBuilder meaning it takes in a string and then a StringBuilder. Now because of currying, this is complete viable:

  appendBuidler "Hi" ?

Where the ? will be filled in at some point. All it knows is that the ? will be a StringBuilder. With this in mind, the chain kind of looks like this:

  StringBuilder() |> append "Hi" ? |> append "There" ? |> append "!" ? |> toString ?

Where every ? is a place holder for the result of the previous method.

Does this save any time? Eh probably not. However, it does show the how useful the |> can be when it comes to workflow like design. For example:

  database |> openAConnection |> getAllUserNames |> closeTheConnection |> Seq.length > 0 |> shouldBeTrue

See if you can figure that one out.

F# and picking a method based on an if statement

I actually saw this first in SICP, but then proceeded to see if F# can do this. Basically it’s an if statement that selects a method to use based on a clause, and then evaluates using two parameters.

  let add x y = x + y
  let sub x y = x - y
  (if 0 = 0 then add else sub) 1 2

As you can see, the parameters stay the same but the actual method called doesn’t. The way it’s written, it evaluates to:

  add 1 2

However, were I to switch the 0 = 0 to 0 = 1 then:

  sub 1 2

Not sure how this would apply to real life, but knowing is the first step.

F# and assigning operators as methods

Once again I have fallen back on F# as the main language of interest. At least until I pick the next one to replace it. Not like I’m wishy washy or anything.

One of the more interesting things about languages like Scheme or Lisp is that nothing is sacred. You can assign characters to methods, and this is possible in f# also.

Here’s an example of a “default” way of defining %% as adding two numbers together.

  let (%%) x y = x + y
  // 1 %% 2 results in 3

As you can see, the %% just looks like a typical operator method. However, it can be changed so that it is actually before the arguments:

  let (!%%) x y = x + y
  // !%% 1 2 results in 3

For anyone who has used Lisp, this should look familiar. It is called Prefix Notation.

Now for something a little more interesting: Take the List.map method. It basically takes a list and applies a method to every member to create a new list. For the C# people, it’s equivalent to someList.Select(x => method(x)). Say you wanted to create a method that just takes a list and “maps” a method to add one to each item.

  let result = List.map (fun y -> y + 1) [1;2;3;]

Pretty simple. Now what if you want to make this a method that takes in a list and applies the same method above to each item?

  let addOne x = List.map (fun y -> y + 1) x
  // addOne [1;2;3] results in 6

Pretty simple again. Now in one more step you can assign operators to do the same:

  let (!+) x = List.map (fun y -> y + 1) x
  // !+ [1;2;3] results in 6

Now I realize this may seem trivial, but it’s actually quiet useful when you start talking about Domain Specific Languages since this allows methods to use non Alpha names.

F#: How F# doesn’t require specifying parameter types in the method signature.

Found this one by mistake when I was trying to figure out how to declare optional parameters in F#. So a typical method signature would be something like this:

 member public x.CreateUserPost(userName:String, password:String) =
   1 = 1

Now let’s say you have a type named LoginModel that takes in two strings in it’s constructor:

type LoginModel(userName:String, password:String) =
  ...

And the it’s added to the method:

member public x.CreateUserPost(userName:String, password:String) =
  new LoginModel(userName, password)

As you can see, LoginModel has its two parameters explicitly typed and because of this they don’t have to be explicitly typed in the method signature. With that in mind you can reduce the method signature to this:

member public x.CreateUserPost(userName, password) =
  new LoginModel(userName, password)

And that’s completely “legal” unlike the complete series of My Little Pony you have on your computer. Shameful.

F#: Use reflection to call a private or protected method

This isn’t anything ground breaking so if you are expecting it to be, tough luck. The world doesn’t revolve around you. It revolves around me.

Making the switch to F# has caused me to redo a lot of older framework stuff and using reflection to call methods is part of that stuff. I could sit here and go on about something and waste your time, but I’ll be nice this time.

open System
open System.Reflection
 module ReflectionUtility =
  //This is used to make sure the GetMethod method doesn't skip private or protected
  let public BindingFlagsToSeeAll =
    BindingFlags.Static |||
    BindingFlags.FlattenHierarchy |||
    BindingFlags.Instance |||
    BindingFlags.NonPublic |||
    BindingFlags.Public;

  type MethodReflection public() =
    //Get the method by the method name from the class type
    member private x.FindMethodInfo<'targetClass>(methodName:String, source:'targetClass) =
      (source.GetType()).GetMethod(methodName, BindingFlagsToSeeAll)

    //Call the find method and run the found method
    member public x.ExecuteMethod<'returnType, 'target>(source:'target, methodName:String, argTypes:Type[], args:Object[]) =
      let info = x.FindMethodInfo(methodName, source)
      info.Invoke(source, args) :?> 'returnType

As you can see, this is extremely easy and short to use. I would suggest adding in some sort of caching if you are using this for anything that needs performance as I’m pretty sure reflection is still somewhat expensive. Most likely if I were caching anything it would be the method info.

If you’re new to F#, or due to an unfortunate turn of events ended up here, you might be wondering what all that ‘word stuff is or how the hell FindMethodInfo is returned

Well the ‘ notation is simply the way F# defines generic types.  It may look odd compared to C# but one nice thing is you never have to worry that your generic constraint might mirror the name of a variable/parameter/field.

The FindMethodInfo does have a return.  F# assumes that the last line in the method is the return.  This is really nice feature that saves a little bit of time by not having to type Return.  The other nice thing about it is that F# will infer the method’s return type by the last line so you never have to type out the return type for a method:

C#:

  public string ReturnString()
  {
    return "";
  }

F#
  member public x.ReturnString() =
    ""

And that’s one reason why all the cool kids use F#.

F#: Creating your own mocks using Object Expressions… Wow

This just in from the “Wow, I can’t believe how easy this is” update desk:

You can roll your own mocks “dynamically”, even when mocking an interface. No, this isn’t too good to be true. No that weird tingling isn’t from your bullsh@# meter going off. (But you really should get that tingling checked by a doctor) This is F#. And this isn’t SPARTA!!! AHRHARHARHRAhRHARHR SO FUNAY!11

Say you have a test method that wants to call a method Validate on the Validator : IValidator class. Here is the IValidator class:

  type IValidator<'a, 'b> =
    abstract AddValidationMethod : ('a -> MethodResult<'b>) -> IValidator<'a, 'b>

(Side note: the ‘a and ‘b are just F#’s generic notation. Generic members are preceeded by a ‘)

Somewhere in your code this IValidator is called by someone, say a controller action:

  member public x.LoginPost(userName:String, password:String) =
    let loginModel = new LoginModel(userName, password)
    let result = x.ControllerValidator.Validate(loginModel)

And of course you would have a controller definition look like this:

  type MainController(validator:IValidator<LoginModel, LoginModel>) =
    inherit Controller()
      member private x.ControllerValidator with get() = validator

So you are set up for mocking.

There are three way, but if you’re already bored (And I assume you are) then just go to 3.

1) Mock the IValidator

As you can imagine, this could be obnoxious to mock up as the AddValidationMethod is adding a method that takes in ‘a and a MethodResult<‘a> and then returns an IValidator<‘a, ‘b>. Can it be done? I would asssume so, but there is another way.

2) Create a new class (Class file) that implements IValidator.

This is the most simple way of doing it. You just make a class that implements IValidator and just pass back what you want. Problem is: This isn’t very reusable as it is now a static class.

3) Create a class on the fly.

And this is the good stuff. F# allows the creation of a class (That implements an interface) “inline”… not sure what word I’m looking for so just go with it.

  let validatorWithFalseReturn = 
    { 
      new IValidator<'a, 'b> with
        member x.AddValidationMethod(methodToAdd:('a -> MethodResult<'b>)) =
          new Validator<'a, 'b>() :> IValidator<'a, 'b>

        member x.Validate(model:'a) =
          (new MethodResult<'b>()).AddErrorMessage("")
    }

    let mainController = new MainController(validatorWithFalseReturn)

(Side note: you might see the :> notation. This is basically the same as (SomeInterface)SomeClass in C#.)

As you can see, I created a new type and set it into the instantiated controller. As you can imagine, you could create a method that takes in a method to set AddValidation to. This has some really great potential like rolling your own mocking system.

So once again F# is looking to be an amazing language.

F#: Duck typing with generic constraints and why you will be speechless

So I’ve been working on a validation design that basically allows validation methods to be added to a list and then run. A small part of it:

    member x.Validate(valueToCheck:'a) =
      methodList 
      |> Seq.map (fun (methodToRun) -> methodToRun(valueToCheck)) 
      |> Seq.reduce (fun(outer) inner -> outer.MergeResults(inner))

What this is saying is take a list of methods, run them and make a list of their results, then merge the results into one. While I won’t get into what the results are (And I almost typed that as resluts which makes me think there is a refurbishing factory for sluts.) just know that each result can merge with another and combine values.

The biggest problem I was running into was a way to allow any method to be added and let the method decide what it needs to run correctly. In C# this can be done easily with dynamic:

  public static MethodResult ValidatePasswordExistence(dynamic modelToCheck)
  {
    var returnResult = new MethodResult(); 
    if (string.IsNullOrEmpty(modelToCheck.Password))
    {
      returnResult = returnResult.AddErrorMessage(UserError.PasswordIsNullOrEmpty);
    }

    return returnResult;
  }

The use of a dynamic parameter means that all validation methods can have the same signature which makes it really easy to send the same class into any method in the list. The problem with F# is there is no ready way to use dynamic and I’m not sure it should be. F# is heavily based on typing and dynamic kind of goes in the opposite direction. So I thought my ship was sunk, that is if I had a ship to sink and said ship hand’t sunk already.

Thanks to some help from the O, i was able to get past this not only without dynamic, but a way to strongly type any object coming into the method:

  let inline UserNameExists (userModel) =
    let userName = (^a : (member UserName : String with get) (userModel))

    let result =
      match userName with 
        | null -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | "" -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | _ -> new MethodResult()

    result

The important part is the second line. This line basically says that anything coming into the method as userModel has to have a property of UserName. One of the dangerous issues with dynamic is there are no compile time checks to make sure that any object going in will have the property or method you need it to. This isn’t true of F#. You not only get to pass in any object you want (That has what is required by the check) but you get complile time errros if you try to pass in an object that doesn’t fit the requirements.

Yup, that’s right. You’re speechless.

F# and using strings for method and class/type names

So after about 2 months of jumping back and forth between languages (Including and not only: Ruby, Python, IronPython, Boo, Scala, and a lot more I don’t remember) I’ve finally settled on F# for more reasons than I will put in this post. BUT one thing that kind of blew me away, and I realize that doesn’t take much (I thought the ending to Terminator 3 was great), was the ability to name methods with string representations… eh wha?

Well I was writing unit tests and stumbled onto the FSUnit “library” (and by “library” I mean a single file). Well on the page there was an example that looked a sumthin’ like this:

[<TestFixture>]
type ``Given a LightBulb that has had its state set to true`` ()=  
  ...

Now if you haven’t used F# just replace “type” with “class”. Essential there is a string/text built name. Not something you see, or at least I haven’t, in any old language. So I went forth and was fruitful and multipled… with unit tests… gross.

[<TestFixture>]
type public ``When Adding``() =
    let returnThing = new MethodResult() :> IResult
    let randomTool = new RandomTool()

    [<Test>]
    member public x.``A Warning Message The Success Flag Is Set To True``() =
        returnThing.AddMessage(new MessageItem(randomTool.RandomString(10), MessageCategory.Warning)).Success |> should be True

And using Resharper’s unit test box thingy it gave a read out of:

  When Adding A Warning Message  
     The Success Flag Is Set To True             Success

Now I’m not sure how useful this is for non unit testing but I think it’s obvious it is to reading Unit Test results. Pretty nice.