schemelist-comprehensionmap-function

Implementing a "Pythonic" map in Scheme: bad idea?


In Scheme, the function (map fn list0 [list1 .. listN]) comes with the restriction that the lists must have the same number of elements. Coming from Python, I'm missing the freedom of Python list comprehensions, which look a lot like map above, but without this restriction.

I'm tempted to implement an alternative "my-map", which allows for lists of differing size, iterating through the first N elements of all lists, where N is the length of the shortest list.

For example, let num be 10 and lst be (1 2 3). With my-map, I hope to write expressions like:

(my-map + (circular-list num) lst)))

And get:

(11 12 13)

I have an easier time reading this than the more conventional

(map + (lambda (arg) (+ num arg)) lst)

or

(map + (make-list (length lst) num) lst) 

Two questions:


Solution

  • First, note that map does allow empty lists, but of course if there's one empty list then all of them should be empty.

    Second, have a look at the srfi-1 version of map -- it is specifically different from the R5RS version as follows:

    This procedure is extended from its R5RS specification to allow the arguments to be of unequal length; it terminates when the shortest list runs out.

    Third, most Scheme programmers would very much prefer

    (map (lambda (arg) (+ num arg)) lst)
    

    My guess is that Scheme is different from Python in a way that makes lambda expressions become more and more readable as you get used to the language.

    And finally, there are some implementations that come with some form of a list comprehension. For example, in Racket you can write:

    (for/list ([arg lst]) (+ num arg))