Skip to content

Instantly share code, notes, and snippets.

@greggirwin
Last active February 11, 2018 04:59
Show Gist options
  • Save greggirwin/aa5615f051ca1b553c952ed460841e02 to your computer and use it in GitHub Desktop.
Save greggirwin/aa5615f051ca1b553c952ed460841e02 to your computer and use it in GitHub Desktop.
Red collect-values and collect-words functions
collect-values: function [
"Collect values in a block, by type or custom parse rule"
block [block!]
rule "Datatype, prototype value, or parse rule"
/deep "Include nested blocks"
/local v
][
rule: switch/default type?/word rule [
datatype! [reduce [rule]] ; Turn a plain datatype into a parse rule for that type.
block! typeset! [:rule] ; Blocks and typesets (e.g. any-word!) work directly as rules.
][reduce [type? rule]] ; Turn a prototype value into a rule for that value's type.
; If they didn't spec /deep, any-block! skips nested blocks.
; /deep does *not* look into nested path or string values.
;!! We need good examples for `parse into` and its limitations.
deep: either deep [[any-path! | any-string! | into top-rule]] [any-block!]
collect [
parse block top-rule: [
any [set v rule (keep/only v) | deep | skip]
]
]
]
blk: [1 a 2 'b 3 c: 4 :d [a 'b c: :d E 'F G: :H]]
print mold collect-values blk any-word!
print mold collect-values/deep blk any-word!
print mold collect-values blk set-word!
print mold collect-values blk [set-word! | get-word!]
print mold collect-values/deep blk [set-word! | get-word!]
print mold collect-values/deep blk first [a:]
print mold collect-values/deep blk integer!
blk: [a/b/c 'j/k/l x/y/z: [d/e/f 'g/h/i t/u/v:]]
print mold collect-values blk path!
print mold collect-values blk lit-path!
print mold collect-values blk set-path!
print mold collect-values/deep blk path!
print mold collect-values/deep blk lit-path!
print mold collect-values/deep blk set-path!
blk: [[a] [b] (c) [[d] (e) ([f])]]
print mold collect-values blk block!
print mold collect-values/deep blk block!
print mold collect-values blk paren!
print mold collect-values blk first [()]
print mold collect-values/deep blk paren!
print mold collect-values blk any-block!
blk: [1 2.0 "b" %file a 3x3 [4.4.4.4 #5 50%]]
print mold collect-values blk [number! | tuple!]
print mold collect-values/deep blk [number! | tuple!]
collect-words: function [
"Collect words used in a block"
block [block!]
/deep "Include nested blocks"
/set "Collect set-words only"
][
word-rule: either set [set-word!][any-word!]
unique either deep [
collect-values/deep block word-rule
][
collect-values block word-rule
]
]
blk: [1 a 2 'b 3 c: 4 :d [a 'b c: :d E 'F G: :H]]
print mold collect-words blk
print mold collect-words/deep blk
print mold collect-words/set blk
print mold collect-words/deep/set blk
@dsgeyser
Copy link

dsgeyser commented Nov 7, 2016

Hi Gregg. Ifind this to be of great value.

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