Q Language looping

|
up vote
down vote[favorite](“http://stackoverflow.com/questions/38553533/looping-in-q-languge#” "“Click”)

|

I am new to Q language and trying to figure out its basics. I am trying a sample program in which let’s say for a given number I can find the sum of all the multiples of 3 and 5?

if input is 10 sum : 23

I am trying to think in terms of using functions like til ,sum and each verb but to no avail till now. Any pointers would be helpful

thanks

|

GitHub Kimtang Kdb-Euler 01.q

Kim

Sent from my iPhone

UNTESTED:

Something like this should work:

sum x where {~&/x mod 3 5} each x:til `int$read0 0


Ryan
[ERROR]: Your autotools build scripts are 200 lines longer than your program. Something’s wrong.
http://kirbyfan64.github.io/

{sum x where ((0=x mod 3) or (0=x mod 5))} til 10

Whoops, there were a few mistakes. Here’s a correct version:

where {not &/[x mod 3 5]} each til 20

You can replace 20 with whatever number it is you want.

There’s lots of looping done under the covers, but loops are hardly ever used because (as you suggest) we can process lists with verbs and adverbs.

q)1 2 3+1 1 1   /the verb + works on lists
2 3 4

q)(+/)til 4  /and advervs like over (/) make verbs that usually take two nouns reduce a list.
6

Your example is a good test to see how much we can reduce an expression to it’s essential parts:

q)x:til 10;sum x where ((0=x mod 3) or (0=x mod 5))
23
q)x:til 10;sum x where (0=x mod 3) or (0=x mod 5)
23
q)x:til 10;sum x where (or/)(0=x mod 3;0=x mod 5)
23
q)x:til 10;sum x where (or/)0=(x mod 3;x mod 5)
23
q)x:til 10;sum x where (or/)0=(x mod/: 3 5)
23
q)x:til 10;sum x where (or/)(0=x mod/:3 5)
23
q)k)x:!10;+/&|/(0=x .q.mod/:3 5)
23

! is til, +/ is sum, & is where, |/ is (or/)

k doesn’t have a primitive mod verb, so use q’s (.q.mod)

On 26/07/2016 1:46 AM, “Ryan Gonzalez” <rymg19@gmail.com> wrote:

UNTESTED:

Something like this should work:

sum x where {~&/x mod 3 5} each x:til `int$read0 0


Ryan
[ERROR]: Your autotools build scripts are 200 lines longer than your program. Something’s wrong.
http://kirbyfan64.github.io/