Skip to content

Commit

Permalink
Merge pull request #68 from sanctuary-js/dc-pair
Browse files Browse the repository at this point in the history
types: define Pair type constructor
  • Loading branch information
davidchambers committed May 12, 2016
2 parents 42616aa + f44c7ca commit 35833e0
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,15 @@ Type comprising every "plain" Object value. Specifically, values created via:
- the `new` operator in conjunction with `Object` or a custom
constructor function.

#### `Pair`

```haskell
$.Pair :: (Type, Type) -> Type
```

Constructor for tuple types of length 2. Arrays are said to represent tuples.
`['foo', 42]` is a member of `Pair String Number`.

#### `PositiveFiniteNumber`

```haskell
Expand Down
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,14 @@
K(true)
);

// Pair :: (Type, Type) -> Type
$.Pair = $.BinaryType(
'sanctuary-def/Pair',
function(x) { return $$typeEq('Array')(x) && x.length === 2; },
function(pair) { return [pair[0]]; },
function(pair) { return [pair[1]]; }
);

// ValidDate :: Type
$.ValidDate = NullaryType(
'sanctuary-def/ValidDate',
Expand Down
26 changes: 26 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,32 @@ describe('def', function() {
'Since there is no type of which all the above values are members, the type-variable constraint has been violated.\n'));
});

it('supports the "Pair" type constructor', function() {
var env = $.env.concat([$.Pair]);
var def = $.create({checkTypes: true, env: env});

// fst :: Pair a b -> a
var fst = def('fst', {}, [$.Pair(a, b), a], R.nth(0));

// snd :: Pair a b -> b
var snd = def('snd', {}, [$.Pair(a, b), b], R.nth(1));

eq(fst(['foo', 42]), 'foo');
eq(snd(['foo', 42]), 42);

throws(function() { fst(['foo']); },
errorEq(TypeError,
'Invalid value\n' +
'\n' +
'fst :: Pair a b -> a\n' +
' ^^^^^^^^\n' +
' 1\n' +
'\n' +
'1) ["foo"] :: Array String\n' +
'\n' +
'The value at position 1 is not a member of ‘Pair a b’.\n'));
});

it('uses R.toString-like string representations', function() {
// f :: Null -> Null
var f = def('f', {}, [$.Null, $.Null], function(x) { return x; });
Expand Down

0 comments on commit 35833e0

Please sign in to comment.