Using System.String.Split from F #

I would like to use the .NET CLR version of String.Split in F #. In particular, I would like to use this code:

let main argv = let s = "Now is the time for FOO good men to come to the aide of their country" let sepAry = [|"FOO"; "BAR"|] let z1 = s.Split sepAry 0 // return an integer exit code 

However, this cannot be compiled due to the fact that the Split version in F # is implemented differently than the version in .Net 4.5. The .NET version I need is:

Split (String [], StringSplitOptions) Returns an array of strings that contains the substrings in this string that are limited to the elements of the given array of strings. The parameter specifies whether to return empty array elements.

I understand that I am getting the version of F # Split that was previously in PowerPack, and therefore the implementation is different from the CLR version.

What is the best way to get what I want? Can I override the F # Split version and use the .Net version? Is it possible to extend the version of F #, and if so, how?

+6
source share
3 answers

The overload you want to use expects a second argument.

 let z1 = s.Split (sepAry, System.StringSplitOptions.None) 

This is not a β€œF # version of Split ”, it’s exactly what Split you see in C #.

+6
source

2 problem here:

  • For .NET BCL, you need to specify () because parameters are declared differently using tuples (see http://msdn.microsoft.com/en-us/library/dd483468.aspx )
  • Only char [] overloads exist without StringSplitOptions. If you want to use a string array, you also need to specify StringSplitOptions.

You can create your own F # overload method, which provides a default value for stringsplitoptions.

0
source

Kirelagin is right, the Split method on the String you are trying to use does not exist, it is only available for char arrays without a secondary argument. You should resort to this version: http://msdn.microsoft.com/en-us/library/tabh47cf.aspx . You should also use parentheses around your arguments when calling none-f # .NET apis, because arguments in C # are defined as a tuple.

You can point your own extension method to String, so you don't need to tell None all the time if this is the expected default behavior

 type System.String with member x.Split(separator : (string [])) = x.Split(separator, System.StringSplitOptions.None) 
0
source

Source: https://habr.com/ru/post/945963/


All Articles