Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foldl(2)/foldr(2): support openArray #24628

Open
wants to merge 2 commits into
base: devel
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions lib/pure/collections/sequtils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func concat*[T](seqs: varargs[seq[T]]): seq[T] =
inc(i)

func addUnique*[T](s: var seq[T], x: sink T) =
## Adds `x` to the container `s` if it is not already present.
## Adds `x` to the container `s` if it is not already present.
## Uses `==` to check if the item is already present.
runnableExamples:
var a = @[1, 2, 3]
Expand Down Expand Up @@ -908,7 +908,7 @@ template foldl*(sequence, operation: untyped): untyped =
multiplication = foldl(numbers, a * b)
words = @["nim", "is", "cool"]
concatenation = foldl(words, a & b)
procs = @["proc", "Is", "Also", "Fine"]
procs = ["proc", "Is", "Also", "Fine"]


func foo(acc, cur: string): string =
Expand All @@ -920,14 +920,13 @@ template foldl*(sequence, operation: untyped): untyped =
assert concatenation == "nimiscool"
assert foldl(procs, foo(a, b)) == "procIsAlsoFine"

let s = sequence
assert s.len > 0, "Can't fold empty sequences"
var result: typeof(s[0])
result = s[0]
for i in 1..<s.len:
let n = sequence.len
assert n > 0, "Can't fold empty sequences"
var result = sequence[0]
for i in 1..<n:
let
a {.inject.} = result
b {.inject.} = s[i]
b {.inject.} = sequence[i]
result = operation
result

Expand Down Expand Up @@ -989,13 +988,12 @@ template foldr*(sequence, operation: untyped): untyped =
assert multiplication == 495, "Multiplication is (5*(9*(11)))"
assert concatenation == "nimiscool"

let s = sequence # xxx inefficient, use {.evalonce.} pending #13750
let n = s.len
let n = sequence.len
assert n > 0, "Can't fold empty sequences"
var result = s[n - 1]
var result = sequence[n - 1]
for i in countdown(n - 2, 0):
let
a {.inject.} = s[i]
a {.inject.} = sequence[i]
b {.inject.} = result
result = operation
result
Expand Down
Loading