a: 5 8 7 2 3 4 1 9
5 8 7 2 3 4 1 9
+/((a!2)*a)^2
165.0
This works because
a
5 8 7 2 3 4 1 9
a!2
1 0 1 0 1 0 1 1
(a!2)*a
5 0 7 0 3 0 1 9
((a!2)*a)^2
25 0 49 0 9 0 1 81.0
+/((a!2)*a)^2
165.0
This approach does not work by first filtering the odd numbers then squaring them then reducing the plus function over them. Instead it relies on turning odd numbers into 1s and even numbers into 0s and then multiplying by the original array. This hack basically preserves all odd numbers and turns even numbers into zeros. I knew this would be okay because I was ultimately going to sum them up.
Is this even a hack though? No array ever got reshaped so maybe this is a good approach?
But what if I just wanted to implement, in K, a function that selected only those elements for which a predicate was true (called filter in other languages, and select in Ruby)?
In other words, how does one write, or _should one write_, something that can do this:
filter {x!2} 5 8 7 2 3 4 1 9
5 7 3 1 9
I looked to see if such a function existed but did not find anything, even on this reference card https://kx.com/technical/contribs/mikep/ReferenceCard.PDF or even in the Kona examples. Did I miss anything? Or is filter not something we normally do? Can indexing operations be done with functions?
--
You received this message because you are subscribed to the Google Groups "Kona Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kona-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Interesting that requests are coming in for this.... I thought that maybe in traditional K applications it was not common, despite it being in nearly every other modern language. I did not know it was built-in in K5.
sumofevensquares: {+/x[&~x!2]^2}
{+/x[&~x!2]^2}
sumofoddsquares: {+/x[&x!2]^2}
{+/x[&x!2]^2}
sumofevensquares (1,2,3,4,5,6)
56.0
sumofoddsquares (1,2,3,4,5,6)
35.0