BlackPearl
BlackPearl

Reputation: 115

how do we iterate and store the results in a variable in kdb

I have a string say example "https://www.google.com" and a count of paging say 5 how do i iterate the URL to append p/page=incrementing numbers of paging and store the result in a variable as list?

"https://www.google.com/page=1"
"https://www.google.com/page=2"
"https://www.google.com/page=3"
"https://www.google.com/page=4"
"https://www.google.com/page=5"

So the end result will look like this having a variable query_var which will hold a list of string example below

query_var:("https://www.google.com/page=1";"https://www.google.com/page=2";"https://www.google.com/page=3";"https://www.google.com/page=4";"https://www.google.com/page=5");
count query_var  \\5

Upvotes: 0

Views: 393

Answers (3)

terrylynch
terrylynch

Reputation: 13572

If you can assume a unique character that doesn't appear elsewhere in your url (e.g. #) then ssr is a simple and easily-readable approach:

ssr["https://www.google.com/page=#";"#";]each string 1+til 5
ssr["https://www.google.com/#/info/history";"#";]each string`aapl`msft`nftx

Upvotes: 3

SJT
SJT

Reputation: 1097

Q1

You don’t even need a lambda to make this a function. It’s a sequence of unary functions, so you can compose them.

q)f: "https://www.google.com/page=",/: string ::
q)f 1+til 6
"https://www.google.com/page=1"
"https://www.google.com/page=2"
"https://www.google.com/page=3"
"https://www.google.com/page=4"
"https://www.google.com/page=5"
"https://www.google.com/page=6"

Q2

q)("https://www.google.com";;"info/history")
enlist["https://www.google.com";;"info/history"]

q)"/"sv'("https://www.google.com";;"info/history")@/: string `aapl`msft`nftx
"https://www.google.com/aapl/info/history"
"https://www.google.com/msft/info/history"
"https://www.google.com/nftx/info/history"

List notation is syntactic sugar for enlist. The list with a missing item is a projection of enlist and can be iterated.

Again, a sequence of unaries is all composable without a lambda:

q)g: "/"sv'("https://www.google.com";;"info/history")@/: string ::
q)g `aapl`msft`nftx
"https://www.google.com/aapl/info/history"
"https://www.google.com/msft/info/history"
"https://www.google.com/nftx/info/history"

Upvotes: 3

James Little
James Little

Reputation: 2069

You can use the join function , with the each-right adverb /:

query_var: "https://www.google.com/page=" ,/: string 1_til 6

Make it a function to support a varied count of pages:

f:{"https://www.google.com/page=" ,/: string 1_til x+1}

q)10=count f[10]
1b

Upvotes: 7

Related Questions