Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why tail recursive function fails for a input for which normal recursive function execute successfully?

As per the MSDN documentation, while writing recursive function, The use of the accumulator argument makes the function tail recursive, which saves stack space. I'm using two example given on the MSDN site to calculate of sum of all the numbers in a list-

first without tail recursion-

let rec Sum myList =
    match myList with
    | [] -> 0
    | h::t -> h + Sum t

and now with tail recursion-

let Sumtail list =
    let rec loop list acc =
        match list with
        | h::t -> loop t acc + h
        | [] -> acc
    loop list 0

and running both the functions with input [1..100000]. Function Sum successfully calculates the sum of this list but gives stackoverflow exception if I pass [1..1000000] but the second function Sumtail fails at [1..100000] while it should give better performance then the first function since it uses tail recursion. Are there any other factors which affects the recursive function?

like image 882
Kapil Avatar asked May 13 '26 05:05

Kapil


1 Answers

Your second function isn't tail-recursive since loop t acc + h is parsed as (loop t acc) + h which makes + become the last operation on loop.

Change loop t acc + h to loop t (acc + h) in order that the function becomes tail-recursive.

like image 97
pad Avatar answered May 19 '26 05:05

pad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!