简体   繁体   中英

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#.

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
        { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM