mapping - 使用来自函数的值生成新序列
问题描述
根据标题,我有以下代码:
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)。
解决方案
发生错误是因为您尝试使用 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)
或者,您可以强制转换int64
like for i in 0 ..< int(n)
,但这可能很危险,具体取决于您传递给 proc 的值。
推荐阅读
- python - 如何平滑深度学习模型中的准确率和损失曲线
- javascript - 在反应中使用导航的动态路线无济于事
- django - django 中的 CK-Editor 无法在生产环境中工作
- azure - 如何使用来自外部资源的 azure 管道参数值
- python - 如何根据我的喜好重复 if else if else 循环?
- python - 如何在 Flask 中使用具有 sudo 权限的 python 包?
- paypal-rest-sdk - 是否可以使用 PayID 检索收据
- c# - 当 Crashlytics 中记录“对象引用未设置为对象的实例”异常时,如何找出哪个对象引用为空?
- javascript - 带有 jquery 的 parseInt 返回 NaN
- java - Java Thread.sleep 在可运行实现中没有按预期工作