I want to create a function to sort an array of for example strings.
This seems to outline the way, but as so often, I struggle with understanding the documentation.
So my questions are:
- What is
Ord
doing? - What is
contramap
doing? - How to then build this function?
CodePudding user response:
What is Ord doing?
Ord
- element which implements Ord
can be ordered and compared. See fp-ts Ord docs and rust docs for more information
This is how it is implemented:
export declare type Ordering = -1 | 0 | 1
export interface Ord<A> {
readonly compare: (second: A) => (self: A) => Ordering
}
N
is a namespace which includes utilities for working with numbers.
What is contramap doing?
Please see the article of fp-ts creator Giulio Canti
. contramap
is a combinator
The goal of a combinator is to create new "things" from previously defined "things".
In this case, contramap
reducec object to the element which is comparable
How to then build this function?
If you have an array of strings, you can get rid of pipe
:
import { sortBy } from 'fp-ts/Array'
import * as S from 'fp-ts/string'
const sortByNameByAge = sortBy([S.Ord])
const persons = ['c','b']
console.log(sortByNameByAge(persons)) // b, c