user5346004
user5346004

Reputation:

How can I make this code tail recursive?

The following code is intended to append two lists.

fun {AppendLists L1 L2}
    if L1 == nil then L2
    else
        L1.1 | {AppendLists L1.2 L2}
    end
end

Upvotes: 1

Views: 223

Answers (2)

francoisr
francoisr

Reputation: 4585

If you don't see why your code is already tail-recursive, here's the same code with a bit less syntactic sugar. Your function as been converted to a procedure with an extra argument to store the result (this is denoted by a facultative '?').

proc {AppendLists L1 L2 ?R} 
  if L1 == nil then L2
  else K in 
     R = L1.1 | K
     {AppendLists L1 L2 K}
  end
end 

Upvotes: 1

rok
rok

Reputation: 2765

This code is already tail-recursive. You have recursion as the last statement, so you are calculating the result first, and then call the recursion.

Upvotes: 0

Related Questions