Tail recursion in mutually recursive functions

I have the following code:

let rec f n =
    if n < 10 then "f" + g (n+1) else "f"
and g n =
    if n < 10 then "g" + f (n+1) else "g"

I want these mutually recursive functions to be recursive for optimization. I tried the following:

let rec fT n = 
    let rec loop a = 
        if n < 10 then "f" + gT (a) else "f"
    loop (n + 1) 
and gT n =
    let rec loop a = 
        if n < 10 then "g" + fT (a) else "g"
    loop (n + 1) 

Is this a faithful recursive version of the tail? If not, a hint in the right direction would be greatly appreciated.

EDIT (second to take a decision):

let rec fA n = 
    let rec loop n a = 
        if n < 10 then loop (n + 1) ("f" + a) else a
    loop n "f"
and gA n =
    let rec loop n a = 
        if n < 10 then loop (n + 1) ("g" + a) else a
    loop n "g"

EDIT (Third solution):

let rec fA n a = 
    if n < 10 then gA (n + 1) (a + "f") else a
and gA n a =
    if n < 10 then fA (n + 1) (a + "g") else a

EDIT (correct solution):

let rec fA n a = 
    if n < 10 then gA (n + 1) (a + "f") else (a + "f")
and gA n a =
    if n < 10 then fA (n + 1) (a + "g") else (a + "g")
+4
source share
2 answers

Your solution is certainly not tail recursive.

"Tail-recursion" - , , . , , : , , - , . , .

, , fT.loop gT, "f" - gT. "f" gT, gT , fT.loop. , .

"" "", " ", . f: g, "f" - g. "f" - "" f . , , , "" . , . , ? - .

: , - , , , .

: f "f" , , " ", , . " " " , , " " ".

"", , , ( , ), . , , .

+6

, .

, . fk gk , f g fk gk

F #, JavaScript. , , , , , . , , ,

// f helper
let fk = (n, k) => {
  if (n < 10)
    return gk(n + 1, g => k("f" + g))
  else
    return k("f")
}
    
// g helper
let gk = (n, k) => {
  if (n < 10)
    return fk(n + 1, f => k("g" + f))
  else
    return k("g")
}
    
let f = n =>
  fk(n, x => x)

let g = n =>
  gk(n, x => x)
  
console.log(f(0))  // fgfgfgfgfgf
console.log(g(0))  // gfgfgfgfgfg
console.log(f(5))  // fgfgfg
console.log(g(5))  // gfgfgf
console.log(f(11)) // f
console.log(g(11)) // g
Hide result
+2

Source: https://habr.com/ru/post/1678195/


All Articles