makeProduct as a functor

When I defined makeProduct, we hadn’t talked about higher-order contracts yet, so it doesn’t work quite right around hom. To fix it, we return a new array whose elements are the results of the contracts given to makeProduct.

var makeProduct = function (cs) {
  arrOf(func)(cs);
  var len = cs.length;
  return function (args) {
    arr(args);
    if (args.length !== len) {
      throw new TypeError('Expected ' +
          len + ' arguments');
    }
    var result = [];
    for (var i = 0; i < len; ++i) {
      // Apply each contract to the
      // corresponding argument.
      result[i] = cs[i](args[i]);
    }
    return result;
  };
};

Written like this, it’s a variant of map where instead of applying the same function to all the members, it applies a list of functions to each respective member. As such, it’s also a functor: you can supply it with either contracts or functions between them.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: