How do you implement "show" tail-recursively?

Haskell is showusually implemented recursively as:

data Tree = Node Tree Tree | Leaf

show' (Node left right) = "(Node " ++ show' left ++ " " ++ show' right ++ ")"
show' Leaf              = "Leaf"

main = putStrLn $ show' (Node (Node Leaf Leaf) Leaf)

How can you implement showusing tail recursion?

+4
source share
2 answers

The use of CPS, as mentioned by M. Shaw.

show' :: Tree -> String
show' = \tree -> go tree id
    where
    go (Node left right) c = 
      go left (\l -> go right (\r -> c ("(Node " ++ l ++ " " ++ r ++ ")")))
    go Leaf c = c "Leaf"

It is important to remember that Haskell tape in many cases eliminates the need for tail recursion. In this case, the tail recursive version must traverse the entire tree before any part of the input can be returned. Try showing an endless tree with each version. When returning a lazy structure, such as Stringin a lazy language, it is better to be core recursive (which is your original implementation) than a tail recursive.

- (++), O(n). , , .

. , , CPS, , .

+6

. wiki.

+4

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


All Articles