Static function in fsharp on usual classes - f#

I constantly call static methods calling the static class, and this seems unnatural to me:
let l = Seq.length myseq
It would be more natural to me to use
let l = myseq.length
you can imagine it is the same for many base class
Is there a way to have all those methods available automatically as instance method, without writing extension methods for each of them ?

Is there a way to have all those methods available automatically as instance method, without writing extension methods for each of them ?
No. And even if you did, you'd lose the benefits of type inference in F#.

In general, there is no way to treat values from modules as if they are instance members. However, in the case of the Seq module, you can find extension member analogs of many of the Seq functions in the System.Linq namespace, so you can do:
open System.Linq
let arr = [| 1 .. 10 |]
let ct = arr.Count()
let arr2 = arr.Select(fun i -> i + 1)
// etc.

How about using the pipe operator?
let l = myseq |> Seq.length
Edit:
Or
let l = myseq.Count()
Edit 2:
As kvb pointed out Count() requires System.Linq

Is it the fact that you don't have Intellisense helping you to see what action is available that bothers you?
Like Umair wrote above, the pipelining style is in a certain way the closest way you're looking for. But indeed, you have to know the right module in which the functions are defined.

Related

How do I register an Arbitrary instance in FsCheck and have xUnit use it?

I've got a type Average with a field count that's a positive int64 and a double field called sum.
I made an arbitrary that generates valid instances with
let AverageGen = Gen.map2 (fun s c -> Average(float(s),int64(int(c))) (Arb.Default.NormalFloat().Generator) (Arb.Default.PositiveInt().Generator) |> Arb.fromGen
How do I get this to be generate arguments with type Average in Property style tests in xUnit?
[<Property>]
static member average_test(av:Average) = ...
type Generators =
static member TestCase() =
{ new Arbitrary<TestCase>() with
override x.Generator =
gen { ...
return TestCase(...) }}
[<Property(Arbitrary=[|typeof<Generators>|])>]
I think Vasily Kirichenko's solution is the correct one, but just for completeness sake, I've also been able to make it work with this imperative function invocation style:
do Arb.register<Generators>() |> ignore
...if you assume a Generators class as in Vasily Kirichenko's answer.
Edit, much later...
While the above, imperative approach may work, I never use it because of its impure nature. Instead, I sometimes use the Arbitrary directly from within the test. With the AverageGen value above (which I'll rename to averageGen, because values should be camelCased), it could look like this:
[<Property>]
let member average_test () =
Prop.forAll averageGen (fun avg ->
// The rest of the test goes here... )

F# quotations, arrays and self-identifier in constructors

I think that's a well-known limitation of F# but I couldn't find any good workarounds…
So, here is the code (I tried to make it as simple as possible, so probably it looks like it doesn't make any sense):
[<ReflectedDefinition>]
type Human (makeAName: unit -> string) as self =
let mutable cats : Cat array = [| |]
do
// get a cat
cats <- Array.append cats [| new Cat (self, makeAName ()) |]
member this.Cats = cats
and
[<ReflectedDefinition>]
Cat (owner : Human, name : string) = class end
The compiler says:
error FS0452: Quotations cannot contain inline assembly code or pattern matching on arrays
Actually it is the combination of as self and array property getter that breaks everything.
The points here are:
I really want to use arrays, because I want WebSharper to translate my collections to JavaSript arrays.
I really need a self-identifier in constructors.
I really need classes (i.e. functional style won't work).
Per-method self-identifiers (member this.Foo) work fine.
One workaround I can think of is making constructors private and using static methods to construct objects. This way I don't need as self. But it is just silly.
Are there any better options?
Update:
Here is an even simpler example:
[<ReflectedDefinition>]
type User (uid: int) as self =
let ROOT_UID = 0
member this.isRoot = (uid = ROOT_UID)
With as self I can't even define a class constant. Well, it's actually a separate question, but I'll ask it here: how do I define a class constant in this particular case?
I do not think it is silly at all. We actually prefer static constructor methods for clarity, even in code that does not use WebSharper. In the whole IntelliFactory codebase we rarely, if ever use self.
You are hitting two annoying limitations of F# compiler and quotations. As you point out, static methods can solve the self problem:
[<ReflectedDefinition>]
type Human private (cats: ref<Cat []>) =
member this.Cats = !cats
static member Create(makeAName: unit -> string) =
let cats = ref [| |]
let h = Human(cats)
let cat = Cat(h, makeAName())
cats := [| cat |]
h
and [<ReflectedDefinition>] Cat (owner: Human, name: string) =
class
end
There are many other ways to accomplish this, for example you can get rid of ref indirection.
Second, you often get FS0452 in ReflectedDefinition code with array operations, even in plain static methods. This usually can be resolved by using library functions instead of direct array access (Array.iter, Array.map).
For the second example, you really want this:
[<ReflectedDefinition>]
module Users =
[<Literal>]
let ROOT_UID = 0
type User(uid: int) =
member this.isRoot = (uid = ROOT_UID)
The [<Literal>] annotation will let you pattern-match on your constants, which can be handy if there is more than one.
For your points:
I really want to use arrays - that should be OK
I really need a self-identifier - it is never necessary, just as constructors are not
I really need classes (i.e. functional style won't work) - definitely not true
Per-method self-identifiers (member this.Foo) work fine - yes, and are useful

Call a function from its name as a string in f#

I thought that I might be able to do this with quotations - but I can't see how.
Should I just use a table of the functions with their names - or is their a way of doing this?
Thanks.
For more info......
I'm calling a lot of f# functions from excel and I wondered if I could write a f# function
let fs_wrapper (f_name:string) (f_params:list double) =
this bit calls fname with f_params
and then use
=fs_wrapper("my_func", 3.14, 2.71)
in the sheet rather than wrap all the functions separately.
You'll need to use standard .NET Reflection to do this. Quotations aren't going to help, because they represent function calls using standard .NET MethodInfo, so you'll need to use reflection anyway. The only benefit of quotations (compared to naive reflection) is that you can compile them, which could give you better performance (but the compilation isn't perfect).
Depending on your specific scenario (e.g. where are the functions located), you'd have to do something like:
module Functions =
let sin x = sin(x)
let sqrt y = sqrt(y)
open System.Reflection
let moduleInfo =
Assembly.GetExecutingAssembly().GetTypes()
|> Seq.find (fun t -> t.Name = "Functions")
let name = "sin"
moduleInfo.GetMethod(name).Invoke(null, [| box 3.1415 |])
Unless you need some extensibility or have a large number of functions, using a dictionary containing string as a key and function value as the value may be an easier option:
let funcs =
dict [ "sin", Functions.sin;
"sqrt", Functions.sqrt ]
funcs.[name](3.1415)
There are many methods but one way is to use Reflection, for instance:
typeof<int>.GetMethod("ToString", System.Type.EmptyTypes).Invoke(1, null)
typeof<int>.GetMethod("Parse", [|typeof<string>|]).Invoke(null, [|"112"|])
GetMethod optionally takes an array of types that define the signature, but you can skip that if your method is unambiguous.
Following up on what Thomas alluded to, have a look at Using and Abusing the F# Dynamic Lookup Operator by Matthew Podwysocki. It offers a syntactically clean way for doing dynamic lookup in F#.

F# Functions vs. Values

This is a pretty simple question, and I just wanted to check that what I'm doing and how I'm interpreting the F# makes sense. If I have the statement
let printRandom =
x = MyApplication.getRandom()
printfn "%d" x
x
Instead of creating printRandom as a function, F# runs it once and then assigns it a value. So, now, when I call printRandom, instead of getting a new random value and printing it, I simply get whatever was returned the first time. I can get around this my defining it as such:
let printRandom() =
x = MyApplication.getRandom()
printfn "%d" x
x
Is this the proper way to draw this distinction between parameter-less functions and values? This seems less than ideal to me. Does it have consequences in currying, composition, etc?
The right way to look at this is that F# has no such thing as parameter-less functions. All functions have to take a parameter, but sometimes you don't care what it is, so you use () (the singleton value of type unit). You could also make a function like this:
let printRandom unused =
x = MyApplication.getRandom()
printfn "%d" x
x
or this:
let printRandom _ =
x = MyApplication.getRandom()
printfn "%d" x
x
But () is the default way to express that you don't use the parameter. It expresses that fact to the caller, because the type is unit -> int not 'a -> int; as well as to the reader, because the call site is printRandom () not printRandom "unused".
Currying and composition do in fact rely on the fact that all functions take one parameter and return one value.
The most common way to write calls with unit, by the way, is with a space, especially in the non .NET relatives of F# like Caml, SML and Haskell. That's because () is a singleton value, not a syntactic thing like it is in C#.
Your analysis is correct.
The first instance defines a value and not a function. I admit this caught me a few times when I started with F# as well. Coming from C# it seems very natural that an assignment expression which contains multiple statements must be a lambda and hence delay evaluated.
This is just not the case in F#. Statements can be almost arbitrarily nested (and it rocks for having locally scoped functions and values). Once you get comfortable with this you start to see it as an advantage as you can create functions and continuations which are inaccessible to the rest of the function.
The second approach is the standard way for creating a function which logically takes no arguments. I don't know the precise terminology the F# team would use for this declaration though (perhaps a function taking a single argument of type unit). So I can't really comment on how it would affect currying.
Is this the proper way to draw this
distinction between parameter-less
functions and values? This seems less
than ideal to me. Does it have
consequences in currying, composition,
etc?
Yes, what you describe is correct.
For what its worth, it has a very interesting consequence able to partially evaluate functions on declaration. Compare these two functions:
// val contains : string -> bool
let contains =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
fun person -> people.Contains(person)
// val contains2 : string -> bool
let contains2 person =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
people.Contains(person)
Both functions produce identical results, contains creates its people set on declaration and reuses it, whereas contains2 creates its people set everytime you call the function. End result: contains is slightly faster. So knowing the distinction here can help you write faster code.
Assignment bodies looking like function bodies have cought a few programmers unaware. You can make things even more interesting by having the assignment return a function:
let foo =
printfn "This runs at startup"
(fun () -> printfn "This runs every time you call foo ()")
I just wrote a blog post about it at http://blog.wezeku.com/2010/08/23/values-functions-and-a-bit-of-both/.

How to create a type that implement IDictionary<'K, 'V> and IEnumerable<'V>

I want to create a read-only keyed collection that implements IDictionary<'K, 'V> and IEnumerable<'V>. Taking the obvious approach I get the following error:
This type implements or inherits the same interface at different generic instantiations 'IEnumerable<'V>' and 'IEnumerable<KeyValuePair<'K,'V>>'. This is not permitted in this version of F#.
Is there a different way of achieving this?
EDIT - Since this seems to be an insurmountable limitation of F#, what would be an idiomatic way of achieving this? One thought that comes to mind is providing members that return the desired view of the data, e.g., member x.List : IList<'V> and member x.Dict : IDictionary<'K, 'V>. Object expressions could be used to provide the implementations. Any other ideas?
One relatively easy approach is to expose the implementation of the two interfaces as members of the type you are writing. This can be done quite nicely using object expressions or just by writing a piece of code that constructs some type and returns it as the result. The second approach would look like this:
type MyCollection<'K, 'V when 'K : equality>(keys:list<'K>, values:list<'V>) = //'
member x.Dictionary =
Seq.zip keys values |> dict
member x.Enumerable =
values |> List.toSeq
The first approach (if you want to implement methods of the interfaces directly would look roughly like this:
type MyCollection<'K, 'V when 'K : equality>(keys:list<'K>, values:list<'V>) = //'
member x.Dictionary =
{ new IDictionary<'K, 'V> with
member d.Add(k, v) = ... }
member x.Enumerable =
// Similarly for IEnumerable
values |> List.toSeq
Exposing the implementations as functions in a module as mentioned by kvb is also a great option - I think that many of the standard F# library types actually do both of the options (so that the user can choose the style he/she prefers). This can be added like this:
module MyCollection =
let toDict (a:MyCollection<_, _>) = a.Dictionary
I'm afraid not. The CLR allows implementation of multiple interfaces of course (even of the same base type), but not the F# language. I believe you won't have any problems if you write the class in C#, but F# is going to give you problems in the current version.
As Noldorin says, this is not possible. One idiomatic approach is to provide toSeq and toDict functions on a module with the same name as your type (like List.toSeq, Array.toSeq, etc.).

Resources