Fully rewritten in functional style