Is there a way to write similar syntax in Nim to convert a split string to hex like example below? Any tips or info is greatly appreciated. Thank you kindly.
Python
Nim
let convertedFromSplit = [for s in splitString: parseHexStr(s)]
Something like this works fine, you can of course choose a different integer type to parse the hex string into:
import std/[strutils, sugar]
let str = "0x42 0xDEADBEEF 0x1"
let data = collect(newSeq):
for part in str.split():
fromHex[int](part)
echo data
The collect from sugar feels a bit awkward. Just use zero-functional for such basic things. And keep asking for proper iterator support in Nim.
import strutils, zero_functional
let
str = "0x42 0xDEADBEEF 0x1"
data = str.split() --> map(fromHex[int](it))
echo data
You can easily put collect on a single line:
import std/[strutils, sugar]
let str = "0x42 0xDEADBEEF 0x1"
let data = collect(newSeq, for part in str.split(): fromHex[int](part))
echo data
@matthesound For your example, I'll simply use mapIt from sequtils:
import std/[strutils, sequtils]
echo "0x42 0xDEADBEEF 0x1".split().mapIt(fromHex[int](it))
Having comprehensions would be still better. Using collect macro is almost as long as allocating the new collection and populating it manually. While the whole point of comprehension is to be a shortcut.
let data = for s in splitString: parseHexStr(s)
Using collect macro is almost as long as allocating the new collection and populating it manually. While the whole point of comprehension is to be a shortcut.
No, the point is to turn a for loop into an expression and Nim's collect accomplishes that successfully and without overhead. It is superior to Python's strange special casing which then cannot be nested easily and has to be rewritten when the code gets more complex... We don't need "shortcuts" that don't compose, it's bad language design.
For this specific case mapIt from sequtils works just fine, but the catch is, these templates don't, eh, compose well. :P They all consume the iteration. As soon as you need to do some additional transformations, they are more or less useless (so most of the time I don't even bother). This is the main selling point of zero_functional - chaining.
Perhaps collect is an acquired taste, I should give it a go.
After some reluctance, as I was used to Python list/dict/set comprehensions, I finally tried collect and I’m rather satisfied with it. I find important that it doesn’t cause any overhead.
I appreciate the procedures and templates from sequtils too (especially those with it) but they create copies. They are really nice to use but not very efficient.
In Python, we can use comprehension with generators and this is very powerful. I’d like to see something like this in Nim.