Skip to content

Commit

Permalink
implements semigroup and monoid for Maybe.
Browse files Browse the repository at this point in the history
  • Loading branch information
diasbruno committed May 22, 2017
1 parent 268af9e commit 377d18b
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/data/maybe/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ module.exports = {
Nothing: Maybe.Nothing,
hasInstance: Maybe.hasInstance,
of: Maybe.of,
empty: Maybe.empty,
fromJSON: Maybe.fromJSON,
[typeSymbol]: Maybe[typeSymbol],
['fantasy-land/of']: Maybe['fantasy-land/of'],
Expand Down
55 changes: 55 additions & 0 deletions src/data/maybe/maybe.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ const assertMaybe = assertType(Maybe);


extend(Just.prototype, {
empty() {
return Nothing();
},

/*~
* isRequired: true
* type: |
Expand All @@ -52,6 +56,12 @@ extend(Just.prototype, {
}
});

extend(Nothing.prototype, {
empty() {
return Nothing();
},
});


/*~~belongsTo: Maybe */
adtMethods(Maybe, {
Expand Down Expand Up @@ -173,6 +183,42 @@ adtMethods(Maybe, {
},


/*~
* type: |
* forall a: (Maybe a).(Maybe a) => Maybe a
*/
concat: {
/*~*/
Nothing: function concat(aMaybe) {
assertMaybe('Maybe.Nothing#concat', aMaybe);
return aMaybe;
},

/*~*/
Just: function concat(aMaybe) {
assertMaybe('Maybe.Just#concat', aMaybe);
return aMaybe.matchWith({
Nothing: () => Just(this.value),
Just: (a) => Just(this.value.concat(a.value))
});
}
},


/*~
* type: |
* forall a: () => Maybe a
*/
empty: {
Nothing: function empty() {
return Nothing();
},
Just: function empty() {
return Nothing();
}
},


/*~
* deprecated:
* since: 2.0.0
Expand Down Expand Up @@ -232,6 +278,15 @@ Object.assign(Maybe, {
},


/*~
* type: |
* forall a: () => Maybe a
*/
empty() {
return Nothing();
},


/*~
* deprecated:
* since: 2.0.0
Expand Down
20 changes: 20 additions & 0 deletions test/specs-src/data.maybe.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,30 @@ describe('Data.Maybe', () => {
});
});

describe('#concat(a)', () => {
property('Just(a).concat(Nothing()) = Just(a)', 'string', (a) => {
return Just(a).concat(Nothing()).equals(Just(a));
});

property('Nothing().concat(Just(a)) = Nothing()', 'string', (a) => {
return Nothing().concat(Just(a)).equals(Just(a));
});

property('Just(a).concat(Just(b)) = Just(c)', 'string', 'string', (a, b) => {
return Just(a).concat(Just(b)).equals(Just(a.concat(b)));
});
});

describe('Fantasy Land', _ => {
laws.Setoid(Maybe.Just);
laws.Setoid(Maybe.Nothing);

laws.Semigroup(Maybe.Just);
laws.Semigroup(Maybe.Nothing);

laws.Monoid(Maybe.Just);
laws.Monoid(Maybe.Nothing);

laws.Functor(Maybe.Just);
laws.Functor(Maybe.Nothing);

Expand Down

0 comments on commit 377d18b

Please sign in to comment.