首页 > 解决方案 > 使用来自函数的值生成新序列

问题描述

根据标题,我有以下代码:

proc squared(n: int64): int64 = n * n

echo squared(5)

生成以下输出:

25

但是,如果我知道想要使用 填充序列squared,我会写如下内容:

import sequtils

proc squared_seq(n: int64): seq[int64] =
    result = newSeq[int64](n)
    for i in 0 ..< n:
        result[i] = squared(i)

echo squared_seq(5)

我希望这会产生以下输出:

@[0, 1, 4, 9, 16]

但我得到的只是以下错误(result[i] = ...在线):

Error: type mismatch: got <seq[int64], int64, int64>
but expected one of: 
proc `[]=`(s: var string; i: BackwardsIndex; x: char)
proc `[]=`[T, U](s: var string; x: HSlice[T, U]; b: string)
proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T)
proc `[]=`[Idx, T, U, V](a: var array[Idx, T]; x: HSlice[U, V]; b: openArray[T])
template `[]=`(s: string; i: int; val: char)
proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: S)
proc `[]=`[T, U, V](s: var seq[T]; x: HSlice[U, V]; b: openArray[T])
proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T)

最终,这是某种形式的映射,因此我认为这段代码可以工作:

var arr = toSeq(0 ..< 5)
var sq_arr = map(arr, squared)

echo sq_arr

具有与以前相同的预期输出:

@[0, 1, 4, 9, 16]

但我得到了(map在线):

Error: type mismatch: got <seq[int], proc (n: int64): int64{.noSideEffect, gcsafe, locks: 0.}>
but expected one of: 
proc map[T](s: var openArray[T]; op: proc (x: var T) {.closure.})
first type mismatch at position: 2
required type: proc (x: var T){.closure.}
but expression 'squared' is of type: proc (n: int64): int64{.noSideEffect, gcsafe, locks: 0.}
proc map[T, S](s: openArray[T]; op: proc (x: T): S {.closure.}): seq[S]
first type mismatch at position: 2
required type: proc (x: T): S{.closure.}
but expression 'squared' is of type: proc (n: int64): int64{.noSideEffect, gcsafe, locks: 0.}

我究竟做错了什么?

(我使用的是 Nim 0.19.0,但它也不适用于 Nim 0.18.0)。

标签: mappingnim-lang

解决方案


发生错误是因为您尝试使用 anint64来索引result序列。int使用通用平台类型访问序列,取决于您的平台,它可能是 32 位长或 64 位。您可以将squared_seq参数更改为int,它应该编译:

import sequtils

proc squared(n: int64): int64 = n * n

proc squared_seq(n: int): seq[int64] =
    result = newSeq[int64](n)
    for i in 0 ..< n:
        result[i] = squared(i)

echo squared_seq(5)

或者,您可以强制转换int64like for i in 0 ..< int(n),但这可能很危险,具体取决于您传递给 proc 的值。


推荐阅读