Created
September 2, 2019 03:29
-
-
Save jejones3141/6f26214b4cc8b3556caeae0b506bb60a to your computer and use it in GitHub Desktop.
Haskell version of code in digitprod.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
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