rewrite in a functional style