View Source Cmp.Comparable protocol (Cmp v0.1.2)
A protocol to define how elements of a type can be compared.
The simplest way to define it for a custom struct is to use @derive based on semantical comparison of fields, in the given order:
defmodule MyStruct do
@derive {Cmp.Comparable, using: [:date, :id]}
defstruct [:id, :date]
end
Cmp.sort([
%MyStruct{date: ~D[2020-03-02], id: 100},
%MyStruct{date: ~D[2020-03-02], id: 101},
%MyStruct{date: ~D[2019-06-06], id: 300}
])
[
%MyStruct{date: ~D[2019-06-06], id: 300},
%MyStruct{date: ~D[2020-03-02], id: 100},
%MyStruct{date: ~D[2020-03-02], id: 101}
]
For existing structs that are already implementing a compare/2
function returning :eq | :lt | :gt
, the protocol can simply be
done by passing using: :compare
.
require Protocol
Protocol.derive(Cmp.Comparable, MyStruct, using: :compare)
This is already done for the following modules:
Link to this section Summary
Functions
Defines how to semantically compare two elements of a given type.
Link to this section Types
@type t() :: term()
Type of an element implementing the Comparable
protocol.
Link to this section Functions
Defines how to semantically compare two elements of a given type.
This should return:
:eq
ifleft == right
:lt
ifleft < right
:gt
ifleft > right