periphery
periphery

Reputation: 75

Implementation of map returning list of lists instead of list

I am trying to implement my own version of Python's map function. I am calling it my_map. The constraint is to use functional programming (if statements are permitted, loops are not).

Here's the implementation:

# f is the function it takes in, and ls is the list to apply this function over.
def my_map(f, ls):
    if len(ls) != 1:
        ret = my_map(f, ls[1:])
        return [f(ls[0])] + [ret]
    else:
        return f(ls[0])

But when I run this with the following input:

def f(x):
    return x * x

my_map(f, [1,2,3,4]) returns [1, [4, [9, 16]]]

while map(f, [1,2,3,4]) returns [1, 4, 9, 16], which is what I expect.

Any idea on how I can get my expected results?

Upvotes: 1

Views: 50

Answers (1)

Ry-
Ry-

Reputation: 224942

return [f(ls[0])] + [ret]

should be

return [f(ls[0])] + ret

. You were creating a new, single-element list from ret, but only the first one should be a single-element list.

Also, a generator would probably a lot more efficient. You’re making lots of partial lists.

def my_map(f, ls):
    it = iter(ls)

    def go():
        yield f(next(it))
        yield from go()

    return list(go())

Upvotes: 3

Related Questions