Can I declare mutually recursive functions with attributes in F#? - f#

So; this code compiles fine (although I wouldn't advise running it...):
let rec firstFunc () =
secondFunc ()
and secondFunc () =
firstFunc ()
But! This code does not:
let rec firstFunc () =
secondFunc ()
[<CompiledName "SecondFunc">]
and secondFunc () =
firstFunc ()
Is there a way to work around this limitation?

You can add the attribute after the and and it seems to compile fine.
let rec firstFunc () =
secondFunc ()
and [<CompiledName "SecondFunc">] secondFunc () =
firstFunc ()

If you only need the CompiledName attribute on one function but not both, you could do:
[<CompiledName "SecondFunc">]
let rec secondFunc () =
firstFunc ()
and firstFunc () =
secondFunc ()
But if you need it on both, I haven't found a solution yet.
To follow up on Pierre Irrmann's answer, you could also do the following if you like seeing your attributes on a separate line:
let rec firstFunc () =
secondFunc ()
and [<CompiledName("SecondFunction")>]
secondFunc () =
firstFunc ()
or even:
let rec firstFunc () =
secondFunc ()
and
[<CompiledName("SecondFunction")>]
secondFunc () =
firstFunc ()
The only requirement is that the secondFunc () declaration, and its attribute, must be indented at least one space. So even this would work:
let rec firstFunc () =
secondFunc ()
and
[<CompiledName("SecondFunction")>]
secondFunc () =
firstFunc ()
I don't particularly recommend that last option, though. I've tested it and it works, but it looks ugly. Better to indent a whole indentation level (four or two spaces, whatever you're using) than to get "cute" and indent just a single space in a case like this.

The best I've managed to come up with so far is:
let rec firstFunc () =
fakeSecondFunc ()
and fakeSecondFunc () =
firstFunc ()
[<CompiledName "SecondFunc">]
let secondFunc () =
fakeSecondFunc ()

Related

A computation expression to get the first valid result out, in F#

How can I achieve something like this in a clean way?
let's imagine this simple code:
let a () = checkSomeStuff (); None
let b () = do Something (); Some "thing"
let c () = checkSomethingElse (); None
"getOne" {
do! a()
do! b()
do! c()
}
and it would return the first "Some".
I could achieve this exact behavior by using Result where I'd return the value through an Error and continue through with Ok, but that is not readable / nice:
let a () = checkSomeStuff (); Ok ()
let b () = do Something (); Error "thing"
let c () = checkSomethingElse (); Ok ()
result {
do! a()
do! b()
do! c()
}
this would work, but I'm looking to achieve that without mis-using the Result type. Can it be done with the existing expressions?
You don't need a computation expression for this. F# has a built-in function called Seq.tryPick that applies a given function to successive elements of a sequence, returning the first Some result, if any. You can use tryPick to define getOne like this:
let getOne fs =
fs |> Seq.tryPick (fun f -> f ())
Trying it with your example:
let a () = checkSomeStuff ();
let b () = Something ();
let c () = checkSomethingElse ();
let x = getOne [ a; b; c ]
printfn "%A" x // Some "thing"
Some time ago, I wrote a post about imperative computation expression builder that does something along those lines. You can represent computations as option-returning functions:
type Imperative<'T> = unit -> option<'T>
In the computation builder, the main thing is the Combine operation that represents sequencing of operations, but you need a few others to make it work:
type ImperativeBuilder() =
member x.ReturnFrom(v) = v
member x.Return(v) = (fun () -> Some(v))
member x.Zero() = (fun () -> None)
member x.Delay(f:unit -> Imperative<_>) =
(fun () -> f()())
member x.Combine(a, b) = (fun () ->
match a() with
| Some(v) -> Some(v)
| _ -> b() )
let imperative = new ImperativeBuilder()
You can then reimplement your example - to return a value, you just use return, but you need to combine individual operations using return!, because the builder does not support do!:
let a () = imperative { printfn "one" }
let b () : Imperative<string> = imperative { return "result" }
let c () = imperative { printfn "two" }
let f = imperative {
return! a()
return! b()
return! c()
}
f()
You could create a function that does what you want. But you have to think throughout what you want to do.
So, your logic is.
You execute a function that returns an option
Then you check that option. if it is None you execute another function, if it is Some you return the value.
A function like these could look like this:
let getSome f opt =
match opt with
| None -> f ()
| Some x -> Some x
With such a function, you then could write. ***
let x =
checkSomeStuff ()
|> getSome (fun _ -> Something () )
|> getSome checkSomethingElse
But then i think, hmmm.... isn't there a better name for getSome? In some way i want to say:
Execute some code and check if it is Some, or else pick the next thing.
With this in mind, i think. hmm.... isn't there already a Option.orElse? And yes! There is! There is also a Option.orElseWith function, that fits your need even better. So now, you can write.
let y =
checkSomeStuff ()
|> Option.orElseWith (fun _ -> Something () )
|> Option.orElseWith checkSomethingElse
If you have functions with side-effects, then you should use Option.orElseWith, otherwise, you can just sue Option.orElse
***: I assume you have the following function defined
let checkSomeStuff () =
None
let Something () =
Some "thing"
let checkSomethingElse () =
None

Why F# type inference doesn't work for class or interface?

F# type inference works for only F# related types except for class or interface.
But I don't know why. I understand candidates will increase, but it's impossible? Are there other reasons?
It's simply impossible to determine what the type is of an object in many circumstances. The most basic case being something like:
type A () = member x.bar () = ()
type B () = member x.bar () = ()
let foo x = x.bar () // Is x A or B?
The compiler does its best though, so if it knows what the type is at the time of usage it will happily allow you to skip the annotations:
type A () = member x.bar () = ()
type B () = member x.bar () = ()
let blah (x: A) = x.bar ()
let foo x =
blah x
x.bar () // x is known to be A thanks to above line
A more in depth discussion can be found in my old question here: Why is type inference impractical for object oriented languages?

How to calculate a result based on or-else of many expensive computations in F#

Assuming I have the following pseudo-C# code:
TResult MyMethod()
{
var firstTry = SomeExpensiveComputation1();
if (firstTry.IsSuccessful) return firstTry;
var secondTry = SomeExpensiveComputation2();
if (secondTry.IsPartiallySuccessful)
{
var subTry1 = SomeExpensiveComputationOn2_1(secondTry);
if (subTry1.IsSuccessful) return subTry1;
var subTry1 = SomeExpensiveComputationOn2_2(secondTry);
if (subTry1.IsSuccessful) return subTry1;
}
return LastExpensiveComputationThatNeverFails();
}
If I were to do this in F#, it'd look like this:
let MyMethod () =
let firstTry = SomeExpensiveComputation1 ()
if firstTry.IsSuccessful then firstTry else
let secondTry = SomeExpensiveComputation2 ()
if secondTry.IsSuccessful then
let subTry1 = SomeExpensiveComputationOn2_1 ()
if subTry1.IsSuccessful then subTry1 else
let subTry2 = SomeExpensiveComputationOn2_2 ()
if subTry2.IsSuccessful then subTry2 else LastExpensiveComputationThatNeverFails ()
else
LastExpensiveComputationThatNeverFails()
As you can see above, I had to repeat LastExpensiveComputationThatNeverFails twice. This doesn't have to be a method call, it can be many lines of inline computations (e.g. try to get some value from cache, if it doesn't exist calculate it.) One could refactor the code into another function, but I still don't like how the same code, even if it's just one line, has to be written twice (or more), as it leads to duplication and messy maintenance. What is the correct way to write such code in F#?
I think it's fine to make LastExpensiveComputationThatNeverFails a local function that is called whenever the result is needed.
However, one could also change the operations to return Option<_> and use the built-in combinator functions.
let MyMethod () =
SomeExpensiveComputation1 ()
|> Option.orElseWith
( fun () ->
SomeExpensiveComputation2 ()
|> Option.bind (fun _ -> SomeExpensiveComputationOn2_1 () |> Option.orElseWith SomeExpensiveComputationOn2_2)
)
|> Option.orElseWith LastExpensiveComputationThatNeverFails
Option.orElseWith LastExpensiveComputationThatNeverFails is only executed if the previous result is None which it will be upon failure.

Code breaks when moving recursive types around

During refactoring of some code, I noticed a situation where code breaks when moved around:
type ThingBase () = class end
and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()
// This works, but try moving the Functions type here instead.
If you move the Functions type below the Thing type, the code breaks unexpectedly:
type ThingBase () = class end
and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// This construct causes code to be less generic than indicated by the
// type annotations. The type variable 'T has been constrained to be
// type 'Thing'.
and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// The type ''T' does not match the type 'Thing'.
And no matter what I try, I cannot get this to typecheck. Why is the type inference so stubborn and refusing to generalize the Create method.
By the way, I also attempted F# 4.1 module rec and it also doesn't matter if Create is a function in a module either.
Any insights? To me it seems this should be something the compiler shouldn't have any troubles with.
It will compile if you do this
static member Create<'T when 'T :> ThingBase
and 'T : (new : Unit -> 'T)> () : 'T = new 'T ()
// ^^^^
where the return type is explicitly stated.
Recursive definitions are typechecked left-to-right in two passes; first function/method signatures, then bodies. You need the body (or an explicit return type annotation) to get the result type, so you either need the body to come first, or else the annotation so that it gets solved in the first of the two passes.
I have no idea why the compiler over-constrains the type parameter of the Create method when you move it up. A work-around could be an intrinsic type extension, so you can split the type definition into multiple sections. Which can help to avoid recursive dependencies.
type ThingBase () = class end
type Thing () =
inherit ThingBase ()
type Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () =
new 'T ()
type Thing with
static member Create () = Functions.Create<Thing> ()
If you want to keep moving forward with that pattern, here's how to do it. I'm assuming you want some kind of factory pattern embedded in the base.
Incidentally, when #Fyodor says left-to-right, this also means top-down. So... you may be fighting against this, too, even though the and functionality should logically, be working. I also agree re: flatter hierarchies, but sometimes, we don't get to have the luxury of choice for various reasons.
type ThingBase () = class end
and Thing () =
inherit ThingBase ()
and Functions() =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
and Thing with
static member Create () = Functions.Create<Thing> ()
// typically, I'd prefer
//type Thing with
// static member Create () = Functions.Create<Thing> ()
// or
//module Thing =
// let Create() = Functions.Create<Thing> ()
references:
https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/type-extensions
The below is incorrect. Apparently recursive definitions get two passes of type checking - once for signatures, then for implementations. I'm leaving the answer here anyway, just for reference.
Original answer
Type inference works left to right, in one pass. Once it encountered a call to Functions.Create, it has decided what the signature has to be, and later augmentations can't change that.
It's the same reason that xs |> Seq.map (fun x -> x.Foo) works, but Seq.map (fun x -> x.Foo) xs doesn't: in the first instance the type of x is known from the previous encounter of xs, and in the second instance it's not known, because xs hasn't been encountered yet.
P. S. You don't actually need a recursive group there. There are no recursive dependencies between your types.

Parameterless lambda expressions in F#

I am looking for a way to define Parameterless lambda expressions in F#, much like the following C# example.
var task = () => {
int x = 3;
DoSomething(x);
}
I tried the following
let task = fun _ ->
let x = 3
doSomething x
It compiles but it gives me task : ('a -> unit) what I am actually looking for is task : (unit -> unit)
The MSDN Documentation does not talk about this. What am I missing here ?
it's just
let task = fun () -> // whatever you need
you example would be:
let task = fun () ->
let x = 3
DoSomething(3)
assuming DoSomething is of type int -> unit - if it returns something else you need
let task = fun () ->
let x = 3
DoSomething(3) |> ignore
to get type unit -> unit
Remark:
Usually you don't write let task = fun () -> ... but just let task() = ...
The thing you missed:
if you write fun _ -> () you are saying you want to take some parameter that you don't mind about - so F# will take the most general (being named 'a here) - this would include unit!
() is the only value of type unit (more or less void from C# ... but a true type in F#)

Resources