Refactored merge to use pattern matching

and recursion to avoid the use of vars, like the cool kids do.