# Most concise way to fold tree structures

### Haskell, ~~37~~ 35:

```
data T a=a:*[T a]
(f%g)z(x:*t)=x`f`foldr(g.(f%g)z)z t
```

not counting the type definition. With it, ~~54~~ **52** (shortened by using infix operator, similarly to the answer by *proud haskeller*, but in a different way).

Ungolfed:

```
data Tree a = Node a [Tree a]
foldTree :: (a -> b -> c) -> (c -> b -> b) -> b -> Tree a -> c
foldTree f g z (Node x t) = f x $ foldr (g . foldTree f g z) z t
-- = f x . foldr g z . map (foldTree f g z) $ t
-- 1
-- / \
-- 2 3
-- / \ \
-- 4 5 6
t = Node 1 [Node 2 [Node 4 [], Node 5 []],
Node 3 [Node 6 []]]
result = foldTree (+) (*) 1 t -- ((+)%(*)) 1 t {-
= 1 + product [2 + product[ 4 + product[], 5 + product[]],
3 + product[ 6 + product[]]]
= 1 + product [2 + 5*6, 3 + 7]
= 321 -}
-- product [a,b,c,...,n] = foldr (*) 1 [a,b,c,...,n]
-- = a * (b * (c * ... (n * 1) ... ))
```

This is the `redtree`

("*red*uce *tree*") function from John Hughes paper, "Why Functional Programming Matters", where it is presented in a more verbose formulation.

## F#, ~~70~~ 61

```
let rec r f g a (Node(n,c))=f n<|List.foldBack(g<<r f g a)c a
```

Not going to win the contest, but I think you can't get less with F#

## Haskell, 35

```
data T a=a:>[T a]
h(%)g a(e:>l)=e%foldr(g.h(%)g a)a l
```

the data type declaration is not counted.