0

exists in python an equivalent to Haskell's mapM_ function?

example ("print()" is here only a placeholder for every function with Signature: a -> None):

#pseudo code!!!
map (lambda x: print(x), [1,2,3])

like in Haskell:

mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
> mapM_ print [1,2]
> 1
> 2
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Thomas Meyer
  • 384
  • 1
  • 11

1 Answers1

2

map just creates a lazy iterator. You would have to consume such an iterator (e.g. by calling list on it) in order to harvest the side-effects. Since that wastes memory (as do other collection constructors), the recommended consume recipe uses a zero size collections.deque:

from collections import deque

def consume(iterator):
    deque(iterator, maxlen=0)

Now, you can consume an iterator with a small memory footprint:

lazy = map(print, [1,2,3])  # using lambda here defeats the purpose of functions
consume(lazy)

But TMK this provides little advantage over a simple loop:

for x in [1, 2, 3]:
    print(x)
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 1
    Can also do `print(*iterable, sep="\n")` :D – ddejohn Oct 06 '21 at 16:50
  • +1, FWIW OP was using `print()` as a stand-in for any function which returns `None` so your consume recipe is the actual answer OP needs. – ddejohn Oct 06 '21 at 17:02
  • What's "TMK"? "to my knowledge"? – wjandrea Oct 06 '21 at 19:18
  • @wjandrea I thought so :D no? I'm not the greatest expert in the acronyms the kids use these days. – user2390182 Oct 07 '21 at 05:38
  • @schwobaseggl I've never heard it before. I'd use "AFAIK" ("as far as I know") instead, though personally, I try to avoid using acronyms in answers for maximum clarity, especially for non-native speakers. – wjandrea Oct 07 '21 at 19:25