diff --git a/src/Data/Tuple.php b/src/Data/Tuple.php index 5ae0659..b5f962b 100644 --- a/src/Data/Tuple.php +++ b/src/Data/Tuple.php @@ -12,7 +12,8 @@ * @implements EqInstance> */ class Tuple implements - EqInstance + EqInstance, + \ArrayAccess { /** * (,) :: a -> b -> (a, b) @@ -155,4 +156,40 @@ public function notEquals(EqInstance $other): bool { return !$this->equals($other); } + + public function offsetExists($offset) + { + return $offset == 0 || $offset == 1; + } + + public function offsetGet($offset) + { + if ($offset === 0) { + return $this->fst(); + } + + if ($offset === 1) { + return $this->snd(); + } + + return null; + } + + public function offsetSet($offset, $value) + { + if ($offset == 0) { + $this->a = $value; + } + + if ($offset == 1) { + $this->b = $value; + } + + throw new \Exception('Unknown offset'); + } + + public function offsetUnset($offset) + { + throw new \Exception('Cannot unset!'); + } } diff --git a/tests/TupleTest.php b/tests/TupleTest.php index bd61913..abfa01a 100644 --- a/tests/TupleTest.php +++ b/tests/TupleTest.php @@ -17,6 +17,26 @@ public function testCanCreateTuple(): void $this->assertTupleIs(123, "hello world", $tuple); } + public function testCanUnwrap(): void + { + // todo: is there a better implementation instead of ArrayAccess here? + $tuple = Tuple::new(123, "hello world"); + [$fst, $snd] = $tuple; + + $this->assertEquals(123, $fst); + $this->assertEquals("hello world", $snd); + } + + public function testCanGetNewTuple(): void + { + // todo: no remove this. just make new tuples. + $tuple = Tuple::new(123, "hello world"); + $tuple[0] = 'one'; + $tuple[1] = 'two'; + + $this->assertTupleIs('one', 'two', $tuple); + } + public function testCanSwapTupleValues(): void { $tuple = Tuple::new(123, "hello world")->swap();