Code refactoring

- Replace switches on element type with a discriminated union match
- Refactor pattern handling in rule definition
Fix tests