Skip to content

Function.prototype.compose #1

@gabejohnson

Description

@gabejohnson

This seems like a no-brainer. However, there're some things to consider:

  1. Argument order
  2. Static method?
  3. Arity of composed functions
  4. Arity of composing functions

Argument order

The newly introduced Semigroupoid specification gives an argument order of g.compose(f). I think this is fine. Dispatching functions (Ramda, Sanctuary, etc.) will flip the order anyway.

Static method?

Another possibility is to put this functionality on the Function object

Function.compose(f, g);
// equivalent to
g.compose(f);

Given the long-time variadic bent, I would expect (with my "pragmatic" JS dev hat on) to be able to pass n arguments to Function.compose

Function.compose(f, g, h);
// equivalent to
h.compose(g).compose(f);

Arity of composed functions

My thinking is compose is a binary method as laid out in the spec. See (2).

Arity of composing functions

The obvious answer is1. Another possibility is n for the first applied function and1 for the rest. A counter-intuitive option is to have no restriction. This would prevent future incompatibility. Imagine a native Tuple type and a future where

const sqr = x => x*x;
sqr 5; // 25

const sum = (x=0, ...xs) => xs.length === 0 ? x : sum(...xs);
const t = #(1,2,3,4);
sum t; // 10

const triple = x => #(x, x, x);
sqr.compose(triple).compose(sum)(5); // 75

const either = f => g => (l, r) => r == null ? l : r;
const right = #(null, 42);
const left = #("fail", null);

const incEither = either (x => x + 1) console.error.bind(console);
incEither right; // 43
incEither left; // "fail"

The above allows for an unrealistically FP friendly future, but I don't see the immediate requirement for an arity restriction (save "type" checking). Having such a restriction would rule out this possibility.

Edit: relabel/reorder section headings
Edit: "Static function?" -> "Static method?"
Edit: Remove "obviously"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions