Quantcast
Channel: Haskell: tail recursion version of depth of binary tree - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Haskell: tail recursion version of depth of binary tree

$
0
0

First of all I have two different implementation that I believe are correct, and have profiled them and thinking they are about of the same performance:

depth::Tree a -> Int
depth Empty        = 0
depth (Branch b l r) = 1 + max (depth l) (depth r)


depthTailRec::Tree a -> Int
depthTailRec = depthTR 0 where
           depthTR d Empty          = d 
           depthTR d (Branch b l r) = let dl = depthTR (d+1) l; dr = depthTR (d+1) r in max dl dr 

I was just wondering aren't people are talking about how tail recursion can be beneficial for performance? And a lot of questions are jumping into my head:

  1. How can you make the depth function faster?
  2. I read about something about how Haskell's laziness can reduce the need of tail recursion, is that true?
  3. Is it the truth that every recursion can be converted into tail recursion?
  4. Finally tail recursion can be faster and space efficient because it can be turned into loops and thus reduce the need to push and pop the stack, is my understanding right?

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>