2
\$\begingroup\$

map is a builtin function that takes one function func and one or more iterables, and maps the function to each element in the iterables. I wrote the following function that does the reverse, but it feels like this is such a basic operation that someone must have done this before, and hopefully given a better name to this.

This appears to be a related question with a slightly different solution:

from toolz import curry, compose


@curry
def fmap(funcs, x):
    return (f(x) for f in funcs)


cases = fmap([str.upper, str.lower, str.title])
tuple_of_cases = compose(tuple, cases)
strings = ['foo', 'bar', 'baz']
list(map(tuple_of_cases, strings))
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

First and foremost, the code is not working as posted. One has to add from toolz import curry, compose.

Apart from this I like the solution and striving for more functional programming is probably always better. I also don't know a canonical solution for passing an argument to functions in python

Things I would definitely change:

  1. I would not overdo the functional programming syntax. list(map(...)) should be IMHO written as list comprehension. Even if one does not cast the result of map to a list, I find a generator comprehension to be more readable.

Small stuff:

  1. fmap could get a docstring.

  2. Type information with mypy etc. would be nice.

  3. Perhaps through would be a better name for fmap. At least if one peeks to other languages. (https://reference.wolfram.com/language/ref/Through.html)

  4. Since strings is a constant, it could become uppercase.

  5. Sometimes stuff does not need a separate name if functions are just concatenated and IMHO tuple_of_cases can go.

from toolz import curry, compose


@curry
def fmap(funcs, x):
    return (f(x) for f in funcs)

STRINGS = ['foo', 'bar', 'baz']
cases = compose(tuple, fmap([str.upper, str.lower, str.title]))

[cases(x) for x in STRINGS]
\$\endgroup\$
1
  • \$\begingroup\$ I fixed the missing import in my question. I couldn't really find a suitable name for the concept, but I like through, thanks for pointing me in that direction. \$\endgroup\$ Commented Jul 8, 2021 at 15:17

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.