Refactor `walk` function using pattern matching