复杂类型序列的内联排序

时间:2017-05-27 09:49:55

标签: sorting nim

我有以下问题:

我有一个表映射点ID(uint16)到Pointstuple[x: float64, y: float64])。给定三个点ID,我想创建一个Triangle,它是按其x值排序的点ID的三倍(其次按y值排序)。

我通过向构造函数传递三个点ID和表来创建Triangle。然后它应该从表中选择相应的Point,相应地对它们进行排序,然后返回三角形。

但是,我无法让内联排序工作。在我调用vec.sort的行上抛出错误。我把它粘贴在代码下面。

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")

错误:

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])

由于某种原因,我的内联排序过程存在类型不匹配。它说它得到了void而不是它。发生了什么事?

1 个答案:

答案 0 :(得分:1)

您正确地执行了该操作,但您忘记导入模块algorithm,其中定义了seq的排序。此外,不需要导入system,因为它总是隐式导入。