Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traverse_ equivalent in Python?

In Haskell, we have traverse_, a function that works on Foldable types to fold a structure with an applicative function, discarding any result:

traverse_ :: (Applicative f,Foldable t) => (a -> f b) -> t a -> f ()

So we can for instance do this:

traverse_ putStrLn ["Hello, ","world!"]
traverse_ print (Just 3)

What is the Python equivalent to traverse_? At least for lists?

like image 945
phaazon Avatar asked Mar 15 '26 11:03

phaazon


2 Answers

Just use a simple loop, or list(map(...)) or a comprehension, and don't save references.

For traverse_ putStrLn ["Hello, ","world!"]:

for i in ["Hello, ", "world!"]:
    print(i)

or:

list(map(print, ["Hello, ", "world!"]))

or:

[print(i) for i in ["Hello, ", "world!"]

Note that list(map(...)) and the comprehension will output the returned value [None, None] if you use it at the interactive interpreter. If you want to suppress it there, save a reference. If you use it in a saved script, you don't need to save a reference to suppress the output of the returned value.

like image 92
TigerhawkT3 Avatar answered Mar 17 '26 00:03

TigerhawkT3


Wouldn't this simply be a higher order function that takes as input a function a function f, a list l and calls f on all lists:

def traverse_ (f,l) :
    for li in l :
        f(li)

This will work on lists, tuples, generators, strings,... Which can be seen as a bit the equivalent of Foldable.

Using this in python3 gives:

$ python3
Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def traverse_ (f,l) :
...     for li in l :
...         f(li)
... 
>>> traverse_(print,["Hello, ","world!"])
Hello, 
world!

traverse_ thus basically comes down to a monadic for loop I think. Where the Applicative is performed on all items.

like image 41
Willem Van Onsem Avatar answered Mar 16 '26 23:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!