Rewritten from Scala into Haskell