Search code examples
maple

why map on list generates extra []


Why does

 map(x->print(x),[1,2,3]);

generate

                           1
                           2
                           3
                           []

Where did the [] come from? According to help, .

 The map commands apply fcn to the operands or elements of expr.

and

  op([1,2,3]);

gives

  1, 2, 3

But it seems here that fcn was also applied to the list itself, i.e. op(0,[1,2,3])


Solution

  • This is correct behaviour from map.

    The print command returns NULL.

    foo := print(1);
                          1
    
                        foo :=
    
    lprint(foo);
      NULL
    

    The map command applied to a list will always return a list. The return value of map is not the return value of any of the calls to the first argument (operator) passed to map.

    Let's make another example, with another procedure which returns NULL.

    f := proc(x) NULL; end proc:
    
    map(f, [1,2,3]);
                          []
    

    So every entry of the original list [1,2,3] gets replaced by NULL, which results in an expression sequence of three NULLs, which ends up being NULL. So the final result from applying map here is [NULL] which produces the empty list [].

    bar := NULL, NULL, NULL;
                        bar :=
    
    lprint(bar);            
      NULL
    
    [ NULL, NULL, NULL ];
                          []
    

    If you don't want to see the empty list returned from map on your example then terminate the statement with a full colon.

    If you do it using seq instead of map then the return value will be the just NULL (since it produces the expression-sequence of three NULLs, which as shown above becomes just NULL).

    seq(print(x), x=[1,2,3]);
                                               1
    
                                               2
    
                                               3
    
    lprint(%);               
      NULL