kdb

kdb+/q How to perform a string search replace when dealing with mixed lists


I want to perform a string search replace on a list but the list has items of different sizes so it is more complex

q)d1
"['null', 'work']"
"['verse']"
"['hi', 'fire']"
"['null']"
"['null', 'echo']"
"['pause']"
"['null', 'hi']"
"['null', 'cheek']"
"['lamb', 'null']"

q)fargs
"w"
"h"
"f"
"s"
"a"
q)sargs
"help"
"yes"
"no"
"why"
"when"

Current attempt

{{ssr[x;y;z]}[x;;]'[fargs;sargs]}each d1

I'm expecting to have d1 returned exactly how it looks with any words in sargs replacing any letters in fargs.

What would be the best way to approach this problem?


Solution

  • It's not exactly clear what your desired result is, but this is an implementation that replaces each occurrence of fargs with the corresponding value in sargs.

    q)ssr/[;fargs;sargs]each d1
    "['null', 'yewhyelpork']"
    "['verwhye']"
    "['yewhyi', 'noire']"
    "['null']"
    "['null', 'ecyewhyo']"
    "['pwhenuwhye']"
    "['null', 'yewhyi']"
    "['null', 'cyewhyeek']"
    "['lwhenmb', 'null']"
    

    Note that this is done sequentially i.e. after one replacement if any letters from fargs are introduced they may be replaced later. We can see this using scan (\) instead of over (/):

    q)ssr\[;fargs;sargs]first d1
    "['null', 'helpork']"
    "['null', 'yeselpork']"
    "['null', 'yeselpork']"
    "['null', 'yewhyelpork']"
    "['null', 'yewhyelpork']"