2013-03-24 2 views
4

F 샤프 샘플에서 FluentValidation 라이브러리를 사용하려고했습니다. 하지만 나는 C Sharp 코드를 F Sharp 코드로 변환 할 수 없기 때문에 막혔다.F #에서 C#을 사용하는 라이브러리 사용 #

하지만이 멋진 라이브러리는 프로그래밍 측면의 기능적인 비트를 CSharp에 가져 오기 위해 노력한 것이므로 대신이 라이브러리를 사용하여 FSharp에서만 자체 라이브러리를 만들어야합니다. 그것은 쉽고 적절한 방법이 될 것입니다.

그래서 어떤면에서 더 나은 의견이 필요합니다. 그리고 누군가가 이것을 위해 FSharp 샘플을 만들 수 있다면 좋을 것입니다. 주로 C#에서 유창한 라이브러리를 사용하기 때문에 학습 목적으로 만 사용됩니다. 그리고 저는 F #에서 그들과 함께 가고 싶습니다.

+0

한 가지 가능한 방법 대신에 처음부터 다시 작성하는 F 번호를 작성하는 것 FnUnit이 NUnit을 위해 한 행을 따라 라이브러리 맨 위에있는 DSL. – Mathias

+0

@Mathias 나는 그것을 시도했지만 아직 FSharp에서 아기 단계를 밟고 있기 때문에 모든 람다식이 FSharp 대화 형 식에서 나에게 외계인이된다. FSharp에서 FluentValidation 코드의 샘플을 제공 할 수 있다면 좋을 것입니다. – kunjee

+2

Ramon Snir의 대답은 F #의 FluentValidation 라이브러리로 작업하는 실용적인 방법을 보여줍니다 (아마도 Ignore Extension을 End로 변경했을 것입니다). Mauricio Scheffer는 훌륭한 F # (및 C#) 기반 유효성 검증 예제를 제공합니다. [F #의 적용 가능한 펑터로 검증] (http://bugsquash.blogspot.co.uk/2011/08/validating-with-applicative-functors-in.html)) –

답변

4

F #은 유창한 DSL을 지원하며 유창한 API를 갖춘 여러 F # 라이브러리가 있습니다. F #의의 형식 시스템은 C#을에서 약간 다르다 '의, 그리고 차이의 대부분은 팝업 유창하게 API를 사용하지만, 여전히,이 작품 :

#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 
     { } 
+1

new/then [생성자 구문] (http://msdn.microsoft.com/en-us/library/dd233192.aspx)뿐만 아니라 base 키워드를 통해 유효성 검사기를 참조 할 수도 있습니다. [Fluent validation F #에서] (http://randomnessgoodhacks.blogspot.co.uk/2010/09/fluent-validation-in-f.html). F # 3은 LINQ 표현식을 지원하므로 인용문 사용은 더 이상 필요하지 않습니다. –

+0

@PhillipTrelford 당신은 물론 정확합니다. 저는 제 코드를 기존의 제 스크립트에 기반을 두었습니다.이 스크립트는 좀 더 복잡하고 새로운/새로운 코드를 필요로합니다. 특정 시나리오에 맞게 단순화되도록 편집되었습니다. 예 - 견적을 드릴 필요가 없습니다. –

+0

@PhillipTrelford - 잠깐. 'fun customer -> customer.Surname'은'base.RuleFor (fun customer -> customer.Surname)'에서 LINQ 표현식으로 암시 적으로 캡처됩니다. –