Skip to content

Instantly share code, notes, and snippets.

@ilyash-b
Created March 4, 2022 08:03
Show Gist options
  • Save ilyash-b/909461aee302de7f3286d1470863119f to your computer and use it in GitHub Desktop.
Save ilyash-b/909461aee302de7f3286d1470863119f to your computer and use it in GitHub Desktop.
Recurse into hashes
F recurse_hash(h:Hash, cb:Fun) {
F is_not_hash(x) x is not Hash
h.tr(is_not_hash -> F(val, ctx) {
cb(val, ctx._path)
})
}
test("recurse_hash(Hash, Fun) sum", {
h = {
'a': {'b': 2}
'c': 3
}
sum = collector/0 {
recurse_hash(h, F(val, _path) collect(val))
# Shorter alternative to the above line:
# recurse_hash(h, collect(X))
}
assert(sum, 5)
})
F recurse_hash(h:Hash, pa:PatternAction) {
F is_not_hash(x) x is not Hash
h.tr(is_not_hash -> F(val, ctx) {
if val =~ pa.pattern {
pa::action(val, ctx._path)
}
})
}
test("recurse_hash(Hash, PatternAction) sum", {
h = {
'a': {'b': 2}
'c': 3
'd': 'a string'
'e': 10
}
r = Result({ collector/0 recurse_hash(h, F(val, _path) collect(val)) })
assert(r, Failure)
assert(r, {'val': MethodNotFound})
assert(r, {'val': {'args': [5, 'a string']}})
sum = collector/0 recurse_hash(h, Int -> F(val, _path) collect(val))
assert(sum, 15)
})
@rdje
Copy link

rdje commented Mar 5, 2022

Hi IIya,

Thank you for considering implementing this deep hash-based data structure's walk method.

From what I understand, this recurse_hash() has 2 variants

  • One that accepts a Fun object as its 2nd argument
  • One that accepts a PatternAction object as its 2nd argument
    • I guess the PatternAction is a comprise because in my FR both the condition or pattern and the Action which I called closure were closures

To be honest, I don't understand all of your test examples yet, but that's ok for now.

Well done!

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