Background (F#)
Let there be trees:
type Tree<'T> = Node of 'T * Tree<'T> list
Now lets fold them nicely with a function called...
foldTree f:('a -> 'b -> 'c) -> g:('c -> 'b -> 'b) -> a:'b -> t:Tree<'a> -> 'c
...taking two functions f
and g
, an initial state a
and of course a tree structure t
. Similar to the well known function fold which operates on lists, this function should "merge" siblings with g
and parents with their children with f
resulting in an accumulated simple value.
Example (F#)
The tree...
// 1
// / \
// 2 3
// / \ \
// 4 5 6
let t = Node (1, [Node (2, [Node (4, []); Node (5, [])]); Node (3, [Node (6, [])])])
...passed to foldTree
with the operators for addition and multiplication along with the initial state 1
...
let result = foldTree (+) (*) 1 t
// = (1 + ((2 + ((4 + a) * ((5 + a) * a))) * ((3 + ((6 + a) * a)) * a)))
// = (1 + ((2 + ((4 + 1) * ((5 + 1) * 1))) * ((3 + ((6 + 1) * 1)) * 1)))
...should return the value 321
to result
.
The Challenge
In any programming language, define the function foldTree
in the most concise way you can come up with. Fewest number of characters wins.
g
with starting valuea
, and combined with the node's value throughf
. Judging by the types. \$\endgroup\$