GeckStar
GeckStar

Reputation: 1166

Inline sorting of complex type sequence

I have the following problem:

I have a table mapping point IDs (uint16) to Points (tuple[x: float64, y: float64]). Given three point IDs, I want to create a Triangle which is a triple of point IDs sorted by their x-values (and secondarily sorted by y-values).

I create a Triangle by passing to a constructor the three point IDs and the table. It should then pick the corresponding Points from the table, sort them accordingly, and return the triangle.

However, I cannot manage to get the inline sorting to work. The error is thrown on the line where I call vec.sort. I pasted it below the code.

import tables
import system

type
  Point* = tuple[x: float64, y: float64]
  PointData* = tuple[id: uint16, point: Point]
  Triangle* = tuple[left: uint16, middle: uint16, right: uint16]

proc createTriangle*(p1: uint16, p2: uint16, p3: uint16, pointToPosition: Table[uint16, Point]): Triangle =
  if p1 in pointToPosition and p2 in pointToPosition and p3 in pointToPosition:
    let t1: PointData = (p1, pointToPosition[p1])
    let t2: PointData = (p2, pointToPosition[p2])
    let t3: PointData = (p3, pointToPosition[p3])
    var vec = @[t1, t2, t3]
    vec.sort do (a, b: PointData) -> int:
      result = system.cmp(a.point.x, b.point.x)
      if result == 0:
        result = system.cmp(a.point.y, b.point.y)
    result = (vec[0].id, vec[1].id, vec[2].id)
  else:
    raise newException(SystemError, "tried to create Triangle with unknown point IDs")

The Error:

types.nim(31, 8) Error: type mismatch: got (seq[PointData], void)
but expected one of: 
proc sort[A](t: CountTableRef[A])
proc sort[A, B](t: var OrderedTable[A, B]; cmp: proc (x, y: (A, B)): int)
proc sort[A, B](t: OrderedTableRef[A, B]; cmp: proc (x, y: (A, B)): int)
proc sort[A](t: var CountTable[A])

For some reason there is a type mismatch with my inline sorting proc. It says it got void instead of it. What's going on?

Upvotes: 0

Views: 206

Answers (1)

uran
uran

Reputation: 1336

You're doing it right, except you forgot to import module algorithm, where sort for seqs is defined. Also import system is not needed as it is always imported implicitly.

Upvotes: 1

Related Questions