fantasyland / fantasy-land

Specification for interoperability of common algebraic structures in JavaScript
MIT License
10.08k stars 373 forks source link

Can someone explain me how I should understand Semigroup? #325

Closed Munkyu-Yang closed 3 years ago

Munkyu-Yang commented 4 years ago
fantasy-land/concat :: Semigroup a => a ~> a -> a

Since there are so many as, it's quite confusing though I've read the documentation. Can someone provide me an actual example please?

davidchambers commented 4 years ago

Here are some examples, using S.concat:

> S.concat ('abc') ('def')
'abcdef'

> S.concat ([1, 2, 3]) ([4, 5, 6])
[1, 2, 3, 4, 5, 6]

> S.concat ({x: 1, y: 2}) ({y: 3, z: 4})
{x: 1, y: 3, z: 4}

> S.concat (S.Just ([1, 2, 3])) (S.Just ([4, 5, 6]))
Just ([1, 2, 3, 4, 5, 6])

> S.concat (Sum (18)) (Sum (24))
Sum (42)

S.concat is easier to understand than the underlying fantasy-land/concat methods for several reasons:

Here is an example of invoking a fantasy-land/concat method directly:

> S.Just ('abc') ['fantasy-land/concat'] (S.Just ('def'))
Just ('abcdef')
CrossEye commented 4 years ago

As well ad David's excellent answer, Tom Harding's series on these FantasyLand types is excellent. Semigroups is the fourth entry.

djnzx commented 4 years ago

Just a Monoid without zero value. Operation only. f: (A, A) => A

juboba commented 3 years ago
fantasy-land/concat :: Semigroup a => a ~> a -> a

Since there are so many as, it's quite confusing though I've read the documentation. Can someone provide me an actual example please?

If you want to understand the type signature, reading from left to right:

In David's last example the first S.Just ('abc') is the a before the ~>.

CrossEye commented 3 years ago

@jujoba: There's a typo in the second bullet.

  • a ~> means: The following function is a method of an a (chain is a method of an instance that has a Semigroup)

should read

  • a ~> means: The following function is a method of an a (concat is a method of an instance that has a Semigroup)