Search code examples
schemelispracket

What is the lisp equivalent of javascript's spread operator?


Say I wanted to find the highest square of a bunch of numbers:

(max (map (lambda (x) (* x x)) (range -4 1))) ; I want 16

This doesn't work: max expects to be called like (max 16 9 4 1 0) and I'm calling it like (max '(16 9 4 1 0)).

The operation I want to apply here is the same as Python's asterisk or Javascript's spread operator, but it's neither quoting, unquoting or quasi-quoting...

What is it called in lisp (or Scheme) (or Racket) and how do I perform it? This seems like such a basic operation I'm struggling to find appropriate search terms on Google.

So far the best I've got is a really sad

(argmax (lambda (x) x) (map (lambda (x) (* x x)) (range -4 1))) ; 16 but really sadly so

Solution

  • JavaScript rest syntax was included in ECMA2015 / ES6 and before 2015 you had this syntax:

    Math.max.apply(
      null,
      [-4, -3, -2, 1].map(function (v) {return v*v; }),
    );
    // ==> 16
    

    And Scheme had it already in the 70s:

    (apply max 
           (map (lambda (v) 
                  (* v v)) 
           '(-4 -3 -2 1)))
    ; ==> 16
    

    Note that JS apply is less powerful than that of Scheme / Common Lisp. Eg. you could add extra arguments which JS does not support:

    (apply map list '((1 2 3) (a b c)))
    ; ==> ((1 a) (2 b) (3 c))