是否有可能破坏 Nim 中的序列?
Is it possible to destruct sequence in Nim?
Nim可以获取前N个元素吗?类似于:
let [a, b, ...rest] = "a/b/c".split("/")
P.S.
用例我正在尝试解析“NYSE:MSFT”字符串
proc parse_esymbol*(esymbol: string): tuple[string, string] =
let parts = esymbol.split(":")
assert parts.len == 2, fmt"invalid esymbol '{esymbol}'"
(parts[0], parts[1])
echo parse_esymbol("NYSE:MSFT")
您可以像这样从元组中分配变量:
let (a,b) = ("a","b")
没有 built-in seq 到元组的转换,但是您可以使用这样的小宏来完成:
macro first[T](s:openArray[T],l:static[int]):untyped =
result = newNimNode(nnkPar)
for i in 0..<l:
result.add nnkBracketExpr.newTree(s,newLit(i))
let (a,b) = "a/b/c".split('/').first(2)
目前至少有两个库实现了类似 : unpack and definesugar 中的宏。
import strutils
import unpack
block:
[a, b, *rest] <- "a/b/c/d/e/f".split("/")
echo a,b
echo rest
import definesugar
block:
(a, b, *rest) := "a/b/c/d/e/f".split("/")
echo a,b
echo rest
# output for both
# ab
# @["c", "d", "e", "f"]
最近的讨论:https://forum.nim-lang.org/t/7072
不过对于你的具体用例,我会用 https://nim-lang.github.io/Nim/strscans.html
来实现一些东西
Nim可以获取前N个元素吗?类似于:
let [a, b, ...rest] = "a/b/c".split("/")
P.S.
用例我正在尝试解析“NYSE:MSFT”字符串
proc parse_esymbol*(esymbol: string): tuple[string, string] =
let parts = esymbol.split(":")
assert parts.len == 2, fmt"invalid esymbol '{esymbol}'"
(parts[0], parts[1])
echo parse_esymbol("NYSE:MSFT")
您可以像这样从元组中分配变量:
let (a,b) = ("a","b")
没有 built-in seq 到元组的转换,但是您可以使用这样的小宏来完成:
macro first[T](s:openArray[T],l:static[int]):untyped =
result = newNimNode(nnkPar)
for i in 0..<l:
result.add nnkBracketExpr.newTree(s,newLit(i))
let (a,b) = "a/b/c".split('/').first(2)
目前至少有两个库实现了类似
import strutils
import unpack
block:
[a, b, *rest] <- "a/b/c/d/e/f".split("/")
echo a,b
echo rest
import definesugar
block:
(a, b, *rest) := "a/b/c/d/e/f".split("/")
echo a,b
echo rest
# output for both
# ab
# @["c", "d", "e", "f"]
最近的讨论:https://forum.nim-lang.org/t/7072
不过对于你的具体用例,我会用 https://nim-lang.github.io/Nim/strscans.html
来实现一些东西