I'm following examples on the Internet, but getting compiler Errors. (The Error message seems to be written in a different language?)
Here is the code:
import strutils, sequtils
import algorithm
type
Tup = tuple[amt: float, time: string]
TupSeq = seq[Tup]
const data: TupSeq = @[(amt: 24.95, time: "04:35"),
(amt: 10.45, time: "03:30")
]
# Sort using proc syntax (From goran.krampe.se)
# s.sort(proc(x, y: Fruit) :int =
# cmp(x.origin, y.origin))
data.sort(proc(x, y: Tup): int =
cmp(x.time, y.time) )
for da in data:
echo da.time & " " & $da.amt
And here is the Error message:
sortSeq.nim(15, 5) Error: type mismatch: got (TupSeq, proc (x: Tup, y: Tup): int{.gcsafe, locks: 0.})
but expected one of:
proc sort[T](a: var openArray[T]; cmp: proc (x, y: T): int; order = SortOrder.Ascending)
If I duplicate the syntax in the Error message, I also get errors.. If I comment out the sort statement, it compiles and runs fine. Here is the compiler version.
Nim Compiler Version 0.14.3 (2016-06-13) [MacOSX: amd64]
Copyright (c) 2006-2016 by Andreas Rumpf
Have funI believe you are trying to sort in-place a const sequence.
change
const data: TupSeq
to
var data: TupSeq
and it should work.Super - that did it.
The compiler error messages were not so helpful, but the Forum is the way to go.
Thanks much!
Well, it is not the friendliest error message, but you can compare the two signatures:
provided
(TupSeq, proc (x: Tup, y: Tup): int{.gcsafe, locks: 0.})
vs expected
(a: var openArray[T]; cmp: proc (x, y: T): int; order = SortOrder.Ascending)
Let us remove the annotations from the provided one, getting
(TupSeq, proc (x: Tup, y: Tup): int)
You are not sending the optional parameter order, so let us omit that from the expected one. Also, let us forget parameter names, which are not relevant anyway. You get
(var openArray[T], proc (x, y: T): int)
Now thw two start looking similar. In your case, you know that T is Tup, so specializing the expected signature you get
(var openArray[Tup], proc (x, y: Tup): int)
Expanding TupSeq shows that what you provided has signature
(seq[Tup], proc (x, y: Tup): int)
Now a seq is an openarray, so the only difference is that var at the beginning.
This is because Nim distinguishes mutable and immutable objects by type. Hence what the compiler is telling you is that the first parameter ought to be mutable, but it isn't.