Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/Data/Tuple.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
* @implements EqInstance<Tuple<A,B>>
*/
class Tuple implements
EqInstance
EqInstance,
\ArrayAccess
{
/**
* (,) :: a -> b -> (a, b)
Expand Down Expand Up @@ -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!');
}
}
20 changes: 20 additions & 0 deletions tests/TupleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down