DEV Community

Getting started with fp-ts: Ord

Giulio Canti on March 13, 2019

In the previous blog post about Eq we were dealing with the concept of equality. In this blog post we are going to deal with the concept of order. ...
Collapse
 
gcanti profile image
Giulio Canti

That's the plan, yes

Collapse
 
jollytoad profile image
Mark Gibson

Is there a way to combine Ords that compare individual properties of an object, for example:

const ordWeight: Ord<Weighted> = contramap((a: Weighted) => a.weight, ordNumber)
const ordLabel: Ord<Labelled> = contramap((a: Labelled) => a.label, ordString)

const ordWeightLabel: Ord<Weighted & Labelled> = combinedOrd(ordWeight, ordLabel)

so that ordWeightLabel would order first by weight, and then by label where weights are equal?

Collapse
 
gcanti profile image
Giulio Canti

Yes, Ords form a Semigroup

import { contramap, getSemigroup, Ord, ordNumber, ordString } from 'fp-ts/lib/Ord'

interface Weighted {
  weight: number
}

interface Labelled {
  label: string
}

const ordWeighted: Ord<Weighted> = contramap((a: Weighted) => a.weight, ordNumber)

const ordLabelled: Ord<Labelled> = contramap((a: Labelled) => a.label, ordString)

interface WeightLabel extends Weighted, Labelled {}

const S = getSemigroup<WeightLabel>()

const ordWeightLabel: Ord<WeightLabel> = S.concat(ordWeighted, ordLabelled)

//
// Usage
//

import { sort } from 'fp-ts/lib/Array'

const xs: Array<WeightLabel> = [
  { weight: 3, label: 'b' },
  { weight: 1, label: 'c' },
  { weight: 3, label: 'a' }
]

console.log(sort(ordWeightLabel)(xs))
/*
[ { weight: 1, label: 'c' },
  { weight: 3, label: 'a' },
  { weight: 3, label: 'b' } ]
*/
Collapse
 
belgac_2 profile image
Hans Scheuren

Hi, your library and articles finally made me love typescript. Thanks a lot. I have a question : would an Ord that always returns 0 be enough to transform the semigroup from get Semigroup in a monoid ?

Collapse
 
jollytoad profile image
Mark Gibson

Oh, excellent, thank you very much. I suspected it had something to do with Semigroups, but hadn't managed to make that leap in understanding them yet.

Collapse
 
veevidify profile image
V

Really looking forward to see more articles from this series.
Had my eye on fp-ts for a while but it'd always seemed to me your target audience were more of advanced Haskell/Purescript users.

Collapse
 
andrasferenczi profile image
andrasferenczi

Great article. Just a minor typo I think:

Instances must satisfy the following laws:

Reflexivity: compare(x, x) <= 0, for all x in A

Didn't you mean == instead of <= ? Otherwise the fromCompare method would not work correctly.

Collapse
 
gcanti profile image
Giulio Canti

It's not a typo, please note that Reflexivity + Antisymmetry imply compare(x, x) === 0, for all x in A. However I'll restate the Reflexivity property to make it clearer, thanks for pointing out

Collapse
 
eoksni profile image
Dmitry Mazurok

It mentions a Setoid which I believe was renamed to Eq.