DEV Community

Discussion on: Getting started with fp-ts: Ord

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.