3 ms·
There are no languages where you can sort machines by either name, OS, or RAM without in some way saying which to sort by. That's a straw man: nobody is tellin
by parenthephobia 11y ago
There are no languages where you can sort machines by either name, OS, or RAM without in some way saying which to sort by.
That's a straw man: nobody is telling you that.
But, you are being told there are multiple languages where you can sort machines by their fields without having to write
type byName []Machine
type byOS []Machine
type byRAM []Machine
func (a byName) Len () int {
return len(a)
}
func (a byOS) Len () int {
return len(a)
}
func (a byRAM) Len () int {
return len(a)
}
func (a byName) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byOS) Swap(i, j int) {
a[i], a[j] = a[i], a[i]
}
func (a byRAM) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byName) Less(i, j int) bool {
return a[i].Name < a[j].Name
}
func (a byOS) Less(i, j int) bool {
return a[i].RAM < a[i].RAM
}
func (a byRAM) Less(i, j int) bool {
return a[i].OS < a[j].OS
}
sort.Sort(byName(machines))
sort.Sort(byOS(machines))
sort.Sort(byRAM(machines))
For example, in Julia, you can just do
sort(machines, by=m->m.Name)
sort(machines, by=m->m.OS)
sort(machines, by=m->m.RAM)
The equivalent is possible in any almost modern language. E.g. in C#
machines.OrderBy(m=>m.Name)
machines.OrderBy(m=>m.OS)
machines.OrderBy(m=>m.RAM)
In Haskell
sortBy (comparing Name) machines
sortBy (comparing OS) machines
sortBy (comparing RAM) machines
This is an extensively solved problem in modern programming languages.
As a bonus, the opportunity for making an error each time you want to sort a new type of array in a new way is reduced if you only have to write one line of code each time.