What is the idiomatic way to squeeze (remove empty strings) the sequence
# squeeze the sequence: remove empty strings
import regex
var name = "Hello,%20World@#!"
var pattern = re"[^a-zA-Z!]"
var sq1 = name.split(pattern)
var sq2: seq[string] = @[]
for i, e in sq1:
if e != "":
sq2.add(e)
echo sq2
You can use sequtils.filter it as follows:
# squeeze the sequence: remove empty strings
import regex
import std/sequtils
var name = "Hello,%20World@#!"
var pattern = re"[^a-zA-Z!]"
var sq1 = name.split(pattern)
echo sq1.filterit(it.len != 0)
I think collect is considered idiomatic for this
import regex, sugar
var name = "Hello,%20World@#!"
var pattern = re"[^a-zA-Z!]"
let sq2 = collect(newSeq):
for e in name.split(pattern):
if e != "": e
echo sq2
import re, sugar, sequtils
echo "Hello,%20World@#!".split(re"[^a-zA-Z!]").filter((part) => part != "")
If yo from Ruby, Nim is uncut Gem. Its core is more powerful and flexible than Ruby. But it's not polished, you need to polish it yourself.
proc is_empty*(s: string): bool = s.len == 0
proc is_present*(s: string): bool = not s.is_empty
Doesn't this require an {.inline.}? I know this isn't a guarantee and we're at the mercy of a C compiler, but why not increase our chances? A proc this short (which by the way should be a func) will probably get inlined anyway, but there can be slightly longer cases where it's hard to judge.
On the second thought, for this exact case it's better to make it a template, if you so need this short a function.
Also, perhaps the sequtils should include a retain which works in-place? This is probably closer to the description in the original post here.
If a third-party-lib like zero_functional is an option:
import zero_functional, re
let
sq = "Hello,%20World@#!".split(re"[^a-zA-Z!]") --> filter(it.len > 0)
echo sq
Ah, snap! Thanks a lot. Completely missed it, even though I'd had a feeling something should be there.
Then, here's the first version which actually satisfies the specs :P
import std/[re, sequtils]
let name = "Hello,%20World@#!"
var s = name.split(re"[^a-zA-Z!]")
s.keepIf(proc(s: string): bool = s != "")
echo(s)
Output: @["Hello", "World", "!"]Also, perhaps the sequtils should include a retain which works in-place?
I intentionally avoided in-place version. Because it won't matter for most cases, and immutable version is simpler and less error prone.