From f44c7cae63c218511da87fe22e3800ff68980e7e Mon Sep 17 00:00:00 2001 From: David Chambers Date: Sun, 8 May 2016 23:03:14 -0700 Subject: [PATCH] types: define Pair type constructor --- README.md | 9 +++++++++ index.js | 8 ++++++++ test/index.js | 26 ++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/README.md b/README.md index 3170222..41a0592 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/index.js b/index.js index 504f2db..e237f7d 100644 --- a/index.js +++ b/index.js @@ -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', diff --git a/test/index.js b/test/index.js index 1641165..e91e1a7 100644 --- a/test/index.js +++ b/test/index.js @@ -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; });