Skip to content

Instantly share code, notes, and snippets.

@jejones3141
Created September 2, 2019 03:29
Show Gist options
  • Save jejones3141/6f26214b4cc8b3556caeae0b506bb60a to your computer and use it in GitHub Desktop.
Save jejones3141/6f26214b4cc8b3556caeae0b506bb60a to your computer and use it in GitHub Desktop.
Haskell version of code in digitprod.py
{-
Here's a Haskell equivalent of digitprod.py.
Haskell is a non-strict (aka lazy) pure functional programming language,
and that makes it differ from the code in digitprod.py:
- Haskell uses recursion rather than looping, but has higher-order
functions that let you avoid repeating boilerplate.
- Functions are "first-class citizens" in Haskell, so you can create
them and return them and pass them.
- Haskell lets you write functions in "point free" form. If you look,
you'll see that dpReduce and digitProduct make no mention of their
Int arguments, but they both have one. *Use it carefully*. Past a
certain point it makes code harder to read instead of clearer. Had
I not fed the original version to pointfree.io and found it better,
I'd have left it as it was.
- Despite Guido's dislike of functional programming in Python (or
perhaps I should say of common functional programming functions,
since you can get the effect of map, filter, or the combination of
the two with comprehensions), Python still has itertools and also
functools, and you can write iterate as a generator expression:
def iterate(f, x0):
while True:
yield x0
x0 = f(x0)
-}
import Data.Char (digitToInt)
dpReduce :: Int -> Int
dpReduce = length . takeWhile (> 9) . iterate digitProduct
where digitProduct = product . map digitToInt . show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment