简体   繁体   中英

F# fsharp interop with C# library (CsvHelper)

I have been successfully using a library CsvHelper to do some CSV manipulation in F# (things that I have not been able to accomplish with Fsharp.Data CsvProvider).

In their documentation, they manipulate headers through:

csv.Configuration.PrepareHeaderForMatch = header => header.Replace( " ", string.Empty );

I am trying to do something similar (changing all headers to lowercase), but I haven't figure out how to deal with this delegate.

I'm trying the following, but it doesn't compile.

csv.Configuration.PrepareHeaderForMatch = (fun header -> header.ToLower())

Any help is greatly appreciated.

Thank you.


I have tried @kaefer advice of assigning the "PrepareHeaderForMatch", since it is a C# getter;setter;

csv.Configuration.PrepareHeaderForMatch <- fun header -> header.ToLower()

As noted in my comment, the compiler complaints that of a type mismatch because the c# property is expecting:

System.Func<System.Type, string, string>

在此处输入图片说明

The error you are seeing is probably about type mismatches, or about a function type not supporting the 'equality' constraint. This is because the expression

csv.Configuration.PrepareHeaderForMatch = (fun header -> header.ToLower())

parses as the invocation of the operator Microsoft.FSharp.Core.Operators.(=) with a property getter on the left hand side and an inline function definition on the right hand side. Instead, you want an assignment expression expr <- expr here, with a property setter invocation on the left hand side:

csv.Configuration.PrepareHeaderForMatch <- fun header -> header.ToLower()

In the F# language, the = token is a common source of confusion, because depending on the context it can stand for two different things:

  • The generic equality operator = as above, or
  • A binding in the context of value, function, type or member definitions, for example let x = 42

Edit Turns out that the expected type of the property in question is System.Func<System.Type, string, string> , which means that you need to supply an extra argument which you subsequently do not use. It can be represented by wildcard: fun _ header -> header.ToLower()

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