F# all permutations of C# class - f#

I have a C# class MyClass.
And I would need to implement f# method returning all
possible permutations of items in a IList
Problem is that MyClass contains a method
bool CheckOrder(IList predecessors) returning true if the
instance of MyClass can be placed in the permutation after instances
of MyClass in the parameter. Otherwisem this method returns false.
Please, could anyone advise me how to implement a proper F# function.
Update:
Please, could you outline F# code of the method test considering my C# class having method: bool CheckOrder(IList predecessors)

Your CheckOrder method expects an IList<MyClass>, so we should maybe work with arrays in F#, since arrays implement the IList interface.
For every element in a permutation candidate, we need to check whether all its predecessors in the array are legal. To me, that looks like a job for a fold operation where the fold's state parameter is a tuple of the "array so far" and a boolean success flag.
let checkPermutation (permutation:MyClass[]) =
let prefix, success =
permutation
|> Array.fold (fun (prefix:MyClass[], success) element ->
if not success then
(Array.empty, false) // once failed, the result is false
else
(Array.append [|element|] prefix, element.CheckOrder prefix)
)
(Array.empty, true)
success
Array.append is probably quite inefficient. If this is too slow, you should consider using a ResizeArray (which is the same as a C# List) instead.

Related

How do I write a delegate with params in F#?

I have a C# delegate that I need to replicate in F#:
public delegate object InvokeDelegate(string method, params object[] parameters)
How do I replicate this in F#?
I tried:
type InvokeDelegate = delegate of (string * (obj [])) -> obj
I'm not sure what's special about this, just that calling the delegate on some library functions doesn't work if I use the F# delegates that I've tried.
I thought it might be the params keyword, but I don't know how to do that in F#.
It's a little messy since F# doesn't have params syntax sugar, but here's how you can do it:
open System
type InvokeDelegate = delegate of method: string * [<ParamArray>] parameters: obj [] -> obj
This will compile down into the following C# equivalent delegate:
[Serializable]
[CompilationMapping(SourceConstructFlags.ObjectType)]
public delegate object InvokeDelegate(string method, params object[] parameters);
See here for param arrays: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/parameters-and-arguments#parameter-arrays
And here for delegates: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/delegates
Note that your definition was also a tupled definition (the parentheses did that), compiling down into a delegate with a simple tuple as a parameter. This is probably one of the quirkier areas of F#.

What does that 2 dots mean? What is the difference between 1 and 2?

I have seen a lot of tutorials using dot, while some use 2. What is the actual meaning of this?
Example,
Array().add()
Animation()..addListener(() {})
The .. operator is dart "cascade" operator. Useful for chaining operations when you don't care about the return value.
This is also dart solution to chainable functions that always return this
It is made so that the following
final foo = Foo()
..first()
..second();
Is strictly equals to this:
final foo = Foo();
foo.first();
foo.second();
Just to be a nitpicker, .. isn't actually an operator in Dart, just part of Dart's syntactic sugar.
In addition to the mentioned use of cascades for chaining calls to functions, you can also use it to access fields on the same object.
Consider this code, taken from the Dart documentation:
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
The first method call, querySelector(), returns a selector object. The code that follows the cascade notation operates on this selector object, ignoring any subsequent values that might be returned.
For more information about cascades, check out Dart's outstanding documentation!

F# generalization by overloading

Given the type
type T =
static member OverloadedMethod(p:int) = ()
static member OverloadedMethod(p:string) = ()
Let's suppose we want to create a generic function that resolves to the specific overload based on the type of the parameter. The most intuitive way would be
//Case 1
let inline call o = T.OverloadedMethod o //error
call 3
call "3"
but this, despite the inline definition, doesn't work and the compiler complains
Error FS0041 A unique overload for method 'OverloadedMethod' could not
be determined based on type information prior to this program point. A
type annotation may be needed. Candidates: static member
T.OverloadedMethod : p:int -> unit, static member T.OverloadedMethod :
p:string -> unit
We can achieve what we want though, for example using the "operator trick"
//Case 2
type T2 =
static member ($) (_:T2, p:int) = T.OverloadedMethod(p)
static member ($) (_:T2, p:string) = T.OverloadedMethod(p)
let inline call2 o = Unchecked.defaultof<T2> $ o
call2 3
call2 "3"
The F# compiler here does (apparently) some more work and doesn't simply fall back to the .NET resolution.
Yet, this looks ugly and implies code duplication. It sounds like Case 1 should be possible.
What technical reasons justify this behaviour? My guess is that there is some trade-off (perhaps with .NET interoperability), but couldn't find more information.
EDIT
From the posts I extract this as a reason:
"a trait call is an F# compiler feature, so there must be two different ways of writing a simple call and a trait call. Using the same syntax for both is not convenient because it might be confusing, some uses could arise where a simple call is compiled as a trait call accidentally".
Let's put the question in a different perspective:
Looking at the code, it really seems straightforward what the compiler should do:
1) call is an inline function, so defer compilation to the use site
2) call 3 is an use site, where the parameter is of type int. But T.OverloadedMethod(int) exists, so let's generate a call to it
3) call "3" like previous case with string in place of int
4) call 3.0 error as T.OverloadedMethod(float) doesn't exist
I would really like to see a code example where letting the compiler do this would be a problem that justifies requiring the developer to write the additional code for the trait call.
At the end of the day, isn't one of F# strengths "conciseness and intuitiveness"?
Here we are in presence of a case where it looks like it could be better.
The trade-offs stem from the fact that this it's a completely erased compiler trick. This means that:
C# code can't see (and take advantage of) any call2 function, it can only see your two $ method overloads.
All information about call2 is gone at runtime, meaning you couldn't invoke it through reflection, for example.
It won't show up in call stacks. This may be a good or a bad thing -- for example, in recent versions of the F# compiler, they've selectively inlined certain functions to make async stacktraces a bit nicer.
The F# is baked in at the call site. If your calling code in is assembly A call2 comes from assembly B, you can't just replace assembly B with a new version of call2; you have to recompile A against the new assembly. This could potentially be a backwards compatibility concern.
A rather interesting benefit is that it can lead to drastic performance improvements in specialized cases: Why is this F# code so slow?. On the flip side, I'm sure there are circumstances where it could cause active harm, or just bloat the resulting IL code.
The reason of that behavior is that T.OverloadedMethod o in
let inline call o = T.OverloadedMethod o
is not a trait call. It's rather simple .NET overloading that must be solved at the call site, but since your function type doesn't imply which overload to solve it simply fails to compile, this functionality is desired.
If you want to "defer" the overload resolution you need to do a trait call, making the function inline is necessary but not sufficient:
let inline call (x:'U) : unit =
let inline call (_: ^T, x: ^I) = ((^T or ^I) : (static member OverloadedMethod: _ -> _) x)
call (Unchecked.defaultof<T>, x)
Using an operator saves you many keystrokes by inferring automatically these constraints but as you can see in your question, it requires to include a dummy parameter in the overloads.

Ceylon not implemented error

What is Ceylon's idiom for indicating that a function is not implemented? I often want to see if a design will typecheck before going through the trouble of implementing all the functions. Presumably, this means having the body throw an error, which has type Nothing and can be assigned to any function. This is also useful for sharing example code when the implementation does not matter.
It looks like some people use UnsupportedOperationException from Java like this:
Integer add(Integer a, Integer b) {throw UnsupportedOperationException();}
But that is too verbose to tack onto a bunch of class methods. I am looking for something similar to Scala's cutely named ??? as in:
def add(a: Int, b: Int): Int = ???
Actually, nothing is a built-in top-level getter you can invoke:
Integer add(Integer a, Integer b) => nothing;
It may look like an object being returned, but it actually throws a runtime exception as soon it is reached.

Cyclic function/type dependency in F#

I have a question about the best way to go about the following
I Have a class B, I have a combinator on B,
let foo : B -> int.
I want the class B to have the combinator encapsulated as a method, so I add it with a type extension.
I then later on realize that foo is quite expensive and want to cache it's result with lazy evaluation
So I add a huge clutch to the system by passing the combinator as a function to the constructor and then initializing a field with foo = lazy(foo self) in the constructor.
i.e.
type foo =
class
val x : int Lazy
new (comb) as self = {x=lazy(comb self);}
end
let something (x:foo) = 1
type foo with
new() = foo(something)
this obviously feels wrong
the two options I see for fixing this are 1, make an interface and have foo inherit that interface, 2, make everything a static method and then make combinators out of those static methods(sort of the opposite of attaching them to classes...)
Neither of these are hugely appealing and I was wondering if I missed option 3
Oh, and I haven't been able to get let rec and to work quite right with this, nor would i really want to as "something" in the above statement depends on a function that depends on a function that depends on a function(3 deep).
any advice would be appreciated
I don't think there is anything wrong with your current design. The key point is that if you define the type Foo as well as the extension to the type in a same file (and the same module), then F# will combine the two parts of the definition into a single .NET type. So, the fact that it is defined in two separate parts is just an implementation detail.
If you don't want to expose the constructor that takes the combinator, you can mark it as private. Together with a few additional changes (i.e. use implicit constructor syntax), the snippet would look like this:
type Foo private (comb) as self =
let x : Lazy<int> = lazy comb self
let something (x:Foo) = 1
type Foo with
new() = Foo(something)
If you want to keep something as a separate function, then this is a fine solution. Many numeric types in the F# PowerPack follow this pattern (see for example definition of complex numbers)
I don't quite grok what you're after, but I think this may help:
type foo(comb) as self =
let x = lazy(comb self)
static member something (x:foo) = 1
new() = foo(foo.something)
A type can be recursive with its own static member, so this is a simpler way to write your code.

Resources