mappingcommon-lisp

What is a realistic example for the use of mapc?


I was just thinking about the different mapping functions in common-lisp as described in the hyperspec. I am pretty much used to mapcar and think it is the easiest to understand. But what is a real world example of using mapc? The example in the hyperspec uses it for a side-effect as far as I get it. But why does it return the list argument?

Is there a general rule when such a mapping is favourable over an iteration using loop etc.?


Solution

  • What is a real world example of using mapc?

    (mapc #'print my-list) is clearer than (dolist (x my-list) (print x))

    Why does it return the list argument?

    The functional heritage imposes the thinking that every function should return something useful; for mapc it is the original list.

    I think mapc returns its list argument for the same reason print does - to simplify debugging by sprinkling your code with output. E.g., suppose you do something like

    (mapcar #'important-processing
            list-with-weird-elements)
    

    You want to see what's inside the list while preserving the logic:

    (mapcar #'important-processing
            (mapc #'show-weird-object list-with-weird-elements))
    

    Also, a lot of things in CL are for "hysterical reasons".

    Is there a general rule when such a mapping is favourable over an iteration using loop etc.?

    Only if you already have a function which does what you need, like print above.