gpt4 book ai didi

nim-lang - 从序列中解包多个变量

转载 作者:行者123 更新时间:2023-12-03 15:30:21 25 4
gpt4 key购买 nike

我期待下面的代码打印 chr7 .

import strutils

var splitLine = "chr7 127471196 127472363 Pos1 0 +".split()
var chrom, startPos, endPos = splitLine[0..2]
echo chrom

相反,它打印 @[chr7, 127471196, 127472363] .

有没有办法同时从序列中解压多个值?

如果元素不连续,那么执行上述操作的最简洁方法是什么?例如:
var chrom, startPos, strand = splitLine[0..1, 5]

给出错误:
read_bed.nim(8, 40) Error: type mismatch: got (seq[string], Slice[system.int], int literal(5))
but expected one of:
system.[](a: array[Idx, T], x: Slice[system.int])
system.[](s: string, x: Slice[system.int])
system.[](a: array[Idx, T], x: Slice[[].Idx])
system.[](s: seq[T], x: Slice[system.int])

var chrom, startPos, strand = splitLine[0..1, 5]
^

最佳答案

这可以使用宏来完成。

import macros

macro `..=`*(lhs: untyped, rhs: tuple|seq|array): auto =
# Check that the lhs is a tuple of identifiers.
expectKind(lhs, nnkPar)
for i in 0..len(lhs)-1:
expectKind(lhs[i], nnkIdent)
# Result is a statement list starting with an
# assignment to a tmp variable of rhs.
let t = genSym()
result = newStmtList(quote do:
let `t` = `rhs`)
# assign each component to the corresponding
# variable.
for i in 0..len(lhs)-1:
let v = lhs[i]
# skip assignments to _.
if $v.toStrLit != "_":
result.add(quote do:
`v` = `t`[`i`])

macro headAux(count: int, rhs: seq|array|tuple): auto =
let t = genSym()
result = quote do:
let `t` = `rhs`
()
for i in 0..count.intVal-1:
result[1].add(quote do:
`t`[`i`])

template head*(count: static[int], rhs: untyped): auto =
# We need to redirect this through a template because
# of a bug in the current Nim compiler when using
# static[int] with macros.
headAux(count, rhs)

var x, y: int
(x, y) ..= (1, 2)
echo x, y
(x, _) ..= (3, 4)
echo x, y
(x, y) ..= @[4, 5, 6]
echo x, y
let z = head(2, @[4, 5, 6])
echo z
(x, y) ..= head(2, @[7, 8, 9])
echo x, y
..=宏解包元组或序列分配。您可以使用 var (x, y) = (1, 2) 完成相同的操作,例如,但是 ..=也适用于 seq 和数组,并允许您重用变量。
head模板/宏提取第一个 count元组、数组或序列中的元素并将它们作为元组返回(然后可以像任何其他元组一样使用,例如用于使用 letvar 进行解构)。

关于nim-lang - 从序列中解包多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com