Using System.String.Split from F# - f#

I would like to use the .NET CLR version of String.Split in F#. Specifically 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
This fails to compile however, due to the fact (I believe) that the version of Split in F# is implemented differently than the one in .Net 4.5.
The version from .NET that I would like is:
Split(String[], StringSplitOptions) Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. A parameter specifies whether to return empty array elements.
I understand that I am getting the F# version of Split, which formerly resided in the PowerPack and that is why the implementation differs from the CLR version.
What is the best way to get what I want? Is it possible to override the F# version of Split and use the .Net version? Is it possible to extend the F# version and if so, how?

The overload you want to use expects a second argument.
let z1 = s.Split (sepAry, System.StringSplitOptions.None)
It's not an “F# version of Split”, it's exactly that Split you see in C#.

2 things are the problem here:
For .NET BCL you need to specify (), because the parameters are declared in different way using tuples (See http://msdn.microsoft.com/en-us/library/dd483468.aspx)
Only the char[] overload exists without StringSplitOptions. If you want to use a string array, you also need to specify StringSplitOptions.
You could create your own F# overload method, that provides a default for the stringsplitoptions.

Kirelagin is right, the Split method on String your trying to use doesn't exist, it's only available for char arrays with no secondary argument. You have to resort to this version: http://msdn.microsoft.com/en-us/library/tabh47cf.aspx. Also you have to use parentheses around your arguments when calling none-f# .NET apis because the arguments in C# are defined as a tuple.
You could of cause define your own extension-method on String, this way you don't have to specify None all the time if that is your expected default behavior
type System.String with
member x.Split(separator : (string [])) = x.Split(separator, System.StringSplitOptions.None)

Related

Why is "do" allowed inside a function?

I noticed that the following code compiles and works in VS 2013:
let f() =
do Console.WriteLine(41)
42
But when looking at the F# 3.0 specification I can't find any mention of do being used this way. As far as I can tell, do can have the following uses:
As a part of loop (e.g. while expr do expr done), that's not the case here.
Inside computation expressions, e.g.:
seq {
for i in 1..2 do
do Console.WriteLine(i)
yield i * 2
}
That's not the case here either, f doesn't contain any computation expressions.
Though what confuses me here is that according to the specification, do should be followed by in. That in should be optional due to lightweight syntax, but adding it here causes a compile error (“Unexpected token 'in' or incomplete expression”).
Statement inside a module or class. This is also not the case here, the do is inside a function, not inside a module or a class.
I also noticed that with #light "off", the code doesn't compile (“Unexpected keyword 'do' in binding”), but I didn't find anything that would explain this in the section on lightweight syntax either.
Based on all this, I would assume that using do inside a function this way should not compile, but it does. Did I miss something in the specification? Or is this actually a bug in the compiler or in the specification?
From the documentation on MSDN:
A do binding is used to execute code without defining a function or value.
Even though the spec doesn't contain a comprehensive list of the places it is allowed, it is merely an expression asserted to be of type unit. Some examples:
if ((do ()); true) then ()
let x: unit = do ()
It is generally omitted. Each of the preceding examples are valid without do. Therefore, do serves only to assert that an expression is of type unit.
Going through the F# 3.0 specification expression syntax has do expr as a choice of class-function-or-value-defn (types) [Ch 8, A.2.5] and module-function-or-value-defn (modules) [Ch 10, A.2.1.1].
I don't actually see in the spec where function-defn can have more than one expression, as long all but the last one evaluate to unit -- or that all but the last expression is ignored in determining the functions return value.
So, it seems this is an oversight in the documentation.

F# type declaration based on parameter passed

hey i want to generate a parametrized type in F#
if parameter is present then generate an array of float containing as many number of values as value of parameter
else single float value
i tried the code which is showing error
type val<'mult> =
|Some -> Arr[|1..mult|]
|None -> value
Sadly F# doesn't currently have dependent types. Also see this uservoice asking for pretty much the same thing you want.

Questions about the definition of lazy

On line 5633 in prim-types.fs (v1.9.7.8) there is the following type abbreviation:
type 'T ``lazy`` = Lazy<'T>
I have a few questions about it.
What do the double backticks mean?
Is this definition equivalent to type lazy<'T> = Lazy<'T>? (If not, how is it different?)
The double back ticks are a way of allowing an F# keyword to be used as an identifier. Another example would be
let ``let`` = 42
To answer the second half of your question, generic types in F# can be specified using either the O'Caml-style syntax where the generic parameter precedes the type (e.g 'a list, int array, etc.), or the .NET-style with angle brackets (e.g. list<'a>, array<int>, etc.), so the two definitions are indeed basically equivalent (except that your version as written is syntactically invalid because lazy is a keyword). For multi-parameter generic types, the O'Caml style is deprecated and will generate a warning (e.g. let (m:(int,string) Map) = Map.empty should be rewritten as let (m:Map<int,string>) = Map.empty).

Point-free style with objects/records in F#

I'm getting stymied by the way "dot notation" works with objects and records when trying to program in a point-free functional style (which I think is a great, concise way to use a functional language that curries by default).
Is there an operator or function I'm missing that lets me do something like:
(.) object method instead of object.method?
(From what I was reading about the new ? operator, I think it works like this. Except it requires definition and gets into the whole dynamic binding thing, which I don't think I need.)
In other words, can I apply a method to its object as an argument like I would apply a normal function to its argument?
Short answer: no.
Longer answer: you can of course create let-bound functions in a module that call a method on a given type... For example in the code
let l = [1;2;3]
let h1 = l.Head
let h2 = List.hd l
there is a sense in which "List.hd" is the version of what you want for ".Head on a list". Or locally, you can always do e.g.
let AnotherWay = (fun (l:list<_>) -> l.Head)
let h3 = AnotherWay l
But there is nothing general, since there is no good way to 'name' an arbitrary instance method on a given type; 'AnotherWay' shows a way to "make a function out of the 'Head' property on a 'list<_>' object", but you need such boilerplate for every instance method you want to treat as a first-class function value.
I have suggested creating a language construct to generalize this:
With regards to language design
suggestions, what if
SomeType..Foo optArgs // note *two* dots
meant
fun (x : SomeType) -> x.Foo optArgs
?
In which case you could write
list<_>..Head
as a way to 'functionize' this instance property, but if we ever do anything in that arena in F#, it would be post-VS2010.
If I understand your question correctly, the answer is: no you can't. Dot (.) is not an operator in F#, it is built into the language, so can't be used as function.

F# type inference in format strings

How is it possible for F# to examine format strings at compile time to determine that x has type int in the following definition?
let foo x = sprintf "%d" x`?
Is this hard-coded into the language or could somebody write their own "my_print" function that uses format strings with a different syntax? For example:
let foo x = my_print "{integer}" x
You can read a bit about it in 6.4.17 ('printf' formats) here, but briefly
it's built into the language
string literals can effectively be 'coerced' into the weird 'Format' type
printf and friends expect a first argument of the Format type, making the coercion happen
The net result is that you can build your own printf-style functions, but must use the same %s formats, since that stuff is built-in.
Here is an example of how you can build your own printf-style functions in F#. You can't change the format specifiers (e.g. "%d"), but you can leverage the existing specifiers to build additional string formatting functions that the compiler will type check.

Resources