Something like this, but it doesn't compile:
import sugar
["1","2","3"].((it) => for i in it: echo i)
Background:
I wanted to chain mapIt inside mapIt and since I can't change "it", I had to use map with anon proc.
Then I thought - why not drop two maps and do it manually in proc.
But it doesn't work that way, so I rewrote the whole chain in another way. I'm just curious with this.
import sugar, pipe
discard ["1","2","3"] |> ((it: openArray[int]) => (for i in it: echo(i)))
No output. Is it how I'm supposed to do it?What's the point of using an anonymous proc here? Why not just
for i in ["1", "2", "3"]: echo i
What's the point of using an anonymous proc here?
In this case? No point. In original case:
proc regexSearch*(regex: Regex): Questions =
result.add getQuestions()
.filterIt(Category.B in it.categories)
.filterIt(
[
it.question,
it.asksAbout,
it.safetyRelation
].toseq().concat(sequtils.toseq(values(it.answers))).join(" ").match(regex)
)
I thought I could replace it with:
proc regexSearch*(regex: Regex): Questions =
result.add getQuestions()
.filterIt(Category.B in it.categories)
.filterIt(
[
it.question,
it.asksAbout,
it.safetyRelation
].toseq().((it)=>(for i in it.answers.values: it.add i; return it)).join(" ").match(regex)
)
But that example is overcomplicated already and I haven't even included type defs.
(And in your pipe example, shouldn't it be openArray[string]?)
Of course :) I'm not thinking. I'm in a loop of:
while errors != 0:
compile
readErrors
doSomethingStupid
Weirdly - compiler doesn't complain about this openArray[int].Ok, got it. To use proc, you have to call it, duh.
import sugar, pipe
["1","2","3"] |> ((it: openArray[string]) => (for i in it: echo(i)))()
1
2
3
Still looking for something stdlib only.
pipe is a 7-line macro, moreover it is public domain/unlicense. Copy it into your codebase if you don't want external dependencies?
Nim's very powerful macro system exists exactly for this reason: not everything can be included in the language, so macros allow modifying the language as you need (sort of).
So you can even improve that pipe macro for it to behave like you expect.
It seems that you can chain anonymous procs via std/with.
import std/[with, math]
let x = 10
.toFloat()
.`+`(1)
.`-`(2)
.with(
(proc(a, b, c: float): float =
for k in [a, b, c]:
result += k * k
)(20, 30)
).`+`(0)
.with(
(proc(f: float): float = f + f)()
).pow(3)
.`*`(5)
.sqrt()
echo x
But due to some reason one cannot chain a with directly after another with, or they'll get
Error: redefinition of ':anonymous'
, which is the reason why I chained a .`+`(0) between them.one cannot chain a with directly after another with, or they'll get Error: redefinition of ':anonymous'
@Araq Shall I open an issue for this?
Thank you very much for this solution.
Nim forum really needs e-mail reminders for responses. I've found about your answer only by casually looking at threads in my profile.