Wonder if Nim can chose the most specific proc if multiple proc are matching the call?
To make sortBy function to be able to accept both function and macro arguments. Currently the code below won't compile.
import sugar, algorithm, sequtils
func sortBy*[T, C](list: openarray[T], op: (T) -> C): seq[T] = list.sortedByIt(op(it))
template sortBy*[T](list: openarray[T], key: untyped): seq[T] = list.sortedByIt(it.`key`)
let people = @[(name: "Sarah"), (name: "Jim")]
echo people.sortBy((v) => v.name)
echo people.sortBy(name)
backticks aren't necessary in templates as far as i know. here you go:
import sugar,algorithm,math,sequtils
template sortby[T](list:openArray[T],op:untyped):seq[T] =
when compiles(T.op):
list.sortedByIt(it.op)
else:
list.sortedByIt(op(it))
type
Foo = object
name: string
Hasname = concept c
c.name is string
proc age(f: Hasname): int = ord(f.name[1])
template namesum(x):int = x.name.mapIt(it.ord).sum
let people = collect(newSeq, for x in ["Alex", "Beth", "Charlie", "Diogenes","Echo", "Frenchie"]:
Foo(name: x))
let persons = collect(newSeq, for x in people: (name:x.name))
echo people.sortby(name)
echo people.sortby(age)
echo people.sortby((o:Foo)=>len(o.name))
echo people.sortby(namesum)
echo "-------------------------------------------------------"
echo persons.sortby(name)
echo persons.sortby((o:tuple[name:string])=>len(o.name))
echo persons.sortby(age)
echo persons.sortby(namesum)