Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# fluent library in F#

I was trying to use FluentValidation library in F Sharp sample. But I got stuck as I can't even turn a simple C Sharp code to F Sharp code.

But then I thought that this wonderful library is just trying to bring functional bits of programming side to CSharp, so instead of using this I should create my own library in FSharp only. That will be easy and appropriate way.

So, I need a opinion in that, which way will be better. And if someone can create FSharp sample for this, that will be great. It is just for learning purpose as I mostly use fluent library in C#. And I like to go with them in F#.

like image 529
kunjee Avatar asked Mar 24 '13 05:03

kunjee


1 Answers

F# supports fluent DSLs, and there are several F# libraries with a fluent API. F#'s type system is a bit different from C#'s, and most of the differences pop-up with fluent APIs, but still, this works:

#r @"C:\Users\Ramon\Downloads\FluentValidation\FluentValidation\FluentValidation.dll"

open System
open FluentValidation

type Customer =
    { Surname : string
      Forename : string
      Company : string
      Discout : int
      Address : string
      Postcode : string
      Discount : int
      HasDiscount : bool }

type IRuleBuilder<'T,'Property> with
    member __.Ignore = ()

type CustomerValidator =
    inherit AbstractValidator<Customer>

    new () =
        let beAValidPostcode postcode = true
        base.RuleFor(fun customer -> customer.Surname).NotEmpty().Ignore
        base.RuleFor(fun customer -> customer.Forename).NotEmpty().WithMessage("Please specify a first name").Ignore
        base.RuleFor(fun customer -> customer.Company).NotNull().Ignore
        base.RuleFor(fun customer -> customer.Discount).NotEqual(0).When(fun customer -> customer.HasDiscount).Ignore
        base.RuleFor(fun customer -> customer.Address).Length(20, 250).Ignore
        base.RuleFor(fun customer -> customer.Postcode).Must(beAValidPostcode).WithMessage("Please specify a valid postcode").Ignore
        { }
like image 82
Ramon Snir Avatar answered Sep 23 '22 09:09

Ramon Snir