Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types: define Pair type constructor #68

Merged
merged 1 commit into from
May 12, 2016
Merged
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
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