Yesterday I came across a post on the haskell reddit where somebody posted the following application of replicateM:
1 2 3 |
|
Dark Magic
It obviously results in all three-character combinations of zeros and ones and in general, replicateM x “01” generates all x-character combinations of zeros and ones accordingly.
replicateM is a standard library function and its haddock
documentation says: “replicateM n act performs the action n times,
gathering the results” and its type actually is replicateM :: Monad m
=> Int -> m a -> m [a]
. So replicateM is not a function
explicitly crafted for the purpose of a “get me all x-ary combinations
of my string” task, it is actually defined for all monads. Just
imagine a more obvious application using the IO monad, which performs the action of
printing hello 3 times and gathers the result.
1 2 3 4 5 |
|
It is typical Haskell practice to use a function with such a general look to solve a rather special problem as our original one – to such a degree that it seems like magic to programmers with a different background. Actually, it might look like “dark” magic when you don’t grasp how/why the hell that result comes about in spite of looking at the source of replicateM, and you might start getting annoyed with Haskell altogether if that happens several times… anyway, there is no such thing as (dark) magic ;) so let’s demystify that interesting example!