8

We know that

list(map(f,[1,2],[3,4],[6,7]))

is equivalent to

[f(1,3,6),f(2,4,7)]

I want to know if there is built-in function tolist that is equivalent to [], so that

tolist(a,b,c,d)

is equivalent to [a,b,c,d].

I think such a function is useful in functional programming. Because many functions take list parameter instead of sequence.

Of course, a simple custom way is lambda *x:list(x), but I always feels it is syntactically cumbersome, especially use it in functional programming style like

map(lambda *x:list(x),[1,2],[3,4],[6,7])

So my question is that if there is no such built-in tolist, whether we could build it on the fly more elegantly using FP packages like toolz?

PS: What I actually want to achieve is threaded version of add (I know numpy, but I don't want to use it at the moment)

from toolz.curried import *
import operator as op
def addwise(*args):
    return list(map(compose(reduce(op.add),lambda *x:list(x)),*args))

then

addwise([1,2],[3,4],[6,7])

will gives

[10, 13]
Alper t. Turker
  • 34,230
  • 9
  • 83
  • 115
user15964
  • 2,507
  • 2
  • 31
  • 57

1 Answers1

1

If

function is useful (....) Because many functions take list parameter

it is a good sign that lambda expression is not a right fit. You don't want to repeat yourself every time you want to apply this pattern.

Sadly we are far from Clojure conciseness:

user=> (map + [1 2] [3 4] [6 7])
(10 13)

but we can still express it in a fairly Pythonic and elegant way:

def apply(f):
    def _(*args):
        return f(args)
    return _ 

which can be used as:

from toolz.curried import reduce 

map(apply(reduce(op.add)), [1,2], [3,4], [6,7])

or even better

map(apply(sum), [1,2], [3,4], [6,7])

although in this case map, can be combined with zip:

map(sum, zip([1, 2], [3, 4], [6, 7])))
Community
  • 1
  • 1
Alper t. Turker
  • 34,230
  • 9
  • 83
  • 115