2

Is it possible to get first N elements in Nim? Something like:

let [a, b, ...rest] = "a/b/c".split("/")

P.S.

Use case I'm trying to parse "NYSE:MSFT" string

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")
Alex Craft
  • 13,598
  • 11
  • 69
  • 133
  • 1
    No idea but seems like you will need to use a macro: https://stackoverflow.com/questions/31948131/unpack-multiple-variables-from-sequence Be aware that the macro probably uses an older Nim version so you better try it out on the nim-playground – KingDarBoja Aug 24 '20 at 23:49

2 Answers2

6

You can assign variables from a tuple like this:

let (a,b) = ("a","b")

There isn't a built-in seq to tuple conversion, but you can do it with a little macro like this:

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)
shirleyquirk
  • 1,527
  • 5
  • 21
3

there are currently at least two libraries implementing a macro like the one in this answer: 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"]

recent discussion: https://forum.nim-lang.org/t/7072

For your specific use case though, I would implement something with https://nim-lang.github.io/Nim/strscans.html

pietroppeter
  • 1,433
  • 13
  • 30