简体   繁体   中英

Can I declare mutually recursive functions with attributes in 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 ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM