Skip to content

add tuple support #1

@azjezz

Description

@azjezz

tuple is basically a function that returns all argument as an array, so maybe we can add it here ?

tuples in hack are immutable, the length of the tuple and type of each element are immutable but values are mutable.

example :

<<__EntryPoint>>
async function main(): Awaitable<noreturn> {
  $tuple = foo();

  $tuple[0] = 'bar'; // fine
  $tuple[1] = false; // fine
  $tuple[1] = 'baz' // error
  $tuple[34] = false; // error
  
  exit(0);
}

function foo(): (string, bool) {
  return tuple('hello', true);
}

to implement this, we can do :

function tuple(...$args): array {
  return $args;
}

but this doesn't give the same behavoir as tuples in hack.

the way to do this is create a new object Tuple as :

namespace {
  function tuple(...$args): Tuple {
    return new Tuple(...$args);
  }
  final class Tuple implements Countable, ArrayAccess, Iterator, Serializable, JsonSerializable {
    public function __construct(...$elements);
  }
}

the Tuple class should :

  • maintain the original size ( don't allow adding new elements )
  • maintain the original values type ( when replacing an element, check the old element type and whether it matches )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions