Skip to content

Instantly share code, notes, and snippets.

@theSherwood
Last active August 14, 2020 07:33
Show Gist options
  • Save theSherwood/e2e680e13d86bdd4dd2842b2af449f73 to your computer and use it in GitHub Desktop.
Save theSherwood/e2e680e13d86bdd4dd2842b2af449f73 to your computer and use it in GitHub Desktop.
Python-like Series Comprehensions
Red [
Description: Python-like Series Comprehensions
Date: 14-August-2020
]
produce: func[
src [series!]
/into
buffer [series!]
/local
mapping word wrapped-series filter series result
][
; Unset `filter` as there may be no "if clause" in `src` and we don't
; want to reuse what we may have already set on a previous call.
unset 'filter
parse src [
copy mapping any to 'for
skip
copy word any to 'in
skip
copy wrapped-series any to 'if
skip
copy filter any to end
]
series: do wrapped-series
; Match the `type? series` datatype by default.
result: either into [buffer][to type? series []]
either value? 'filter [
foreach (first word) (series) [
if do filter [append result do mapping]
]
][
foreach (first word) (series) [append result do mapping]
]
result
]
@theSherwood
Copy link
Author

Some examples:

>> a: [1 2 3 4 5 6 7 8 9 10]
== [1 2 3 4 5 6 7 8 9 10]

>> produce [i * 2 for i in a]
== [2 4 6 8 10 12 14 16 18 20]

>> produce [i * 2 for i in a if even? i]
== [4 8 12 16 20]

>> produce/into [i * 2 for i in a if even? i] ""
== "48121620"

>> b: "string"
== "string"

>> produce [rejoin [i "."] for i in b]
== "s.t.r.i.n.g."

>> produce [uppercase x for x in b]
== "STRING"

>> produce [uppercase x for x in b if find "trn" x]
== "TRN"

>> produce/into [uppercase x for x in b if find "trn" x] []
== [#"T" #"R" #"N"]

>> produce/into [rejoin [i "."] for i in b] []
== ["s." "t." "r." "i." "n." "g."]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment