2

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?

phaazon
  • 1,972
  • 15
  • 21
  • I'm not familiar with Haskell, but it sounds like the Python equivalent is a `for` loop. Python's functional features are specifically not designed for operations with side effects. – user2357112 Jan 05 '16 at 09:33

3 Answers3

2

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.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Ok for the loop, but the two later would actually yield a list, right? A list of `None`? – phaazon Jan 05 '16 at 09:40
  • That's right, because the calls have to actually be evaluated. Technically, `print()` also has a return value - `None`. You just don't see `None` in the interpreter after a `print()` call because it specifically skips the output if it's just `None` - you'd have to print it if you wanted to see it (try `print(print('hi'))`). It outputs `[None, None]` because that's not just `None`, it's a `list`. Again, this is just in the interactive interpreter. It's not an issue in a saved script. – TigerhawkT3 Jan 05 '16 at 09:46
1

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

Not sure I understand it correctly, but may be you're looking for a map wrapper:

def traverse(f):
    return lambda L : map(f, L)

print traverse(lambda x : x*x) (range(5)) # [0, 1, 4, 9, 16]
6502
  • 112,025
  • 15
  • 165
  • 265