From 5967b6f60f669f343ed089a4cd09f324cbfc5c69 Mon Sep 17 00:00:00 2001 From: Luis Felipe Manfroni <33612042+luismanfroni@users.noreply.github.com> Date: Mon, 5 Oct 2020 07:02:08 -0300 Subject: [PATCH] doc(sugar): added description and examples to dup (#15455) --- lib/pure/sugar.nim | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/pure/sugar.nim b/lib/pure/sugar.nim index 49934b9bb7..be5e1f326b 100644 --- a/lib/pure/sugar.nim +++ b/lib/pure/sugar.nim @@ -217,7 +217,10 @@ since (1, 1): macro dup*[T](arg: T, calls: varargs[untyped]): T = ## Turns an `in-place`:idx: algorithm into one that works on - ## a copy and returns this copy. + ## a copy and returns this copy, without modifying its input. + ## + ## This macro also allows for (otherwise in-place) function chaining. + ## ## **Since**: Version 1.2. runnableExamples: import algorithm @@ -234,6 +237,21 @@ since (1, 1): var s2 = "xyz" doAssert s1 & s2 == s1.dup(&= s2) + proc makePalindrome(s: var string) = + for i in countdown(s.len-2, 0): + s.add(s[i]) + + var c = "xyz" + + # An underscore (_) can be used to denote the place of the argument you're passing: + # b = "xyz" + var d = dup c: + makePalindrome # xyzyx + sort(_, SortOrder.Descending) # zyyxx + makePalindrome # zyyxxxyyz + + doAssert d == "zyyxxxyyz" + result = newNimNode(nnkStmtListExpr, arg) let tmp = genSym(nskVar, "dupResult") result.add newVarStmt(tmp, arg)