How to start iteration from the second element with this comprehension:
destroy c for c, i in container.children
Cannot find an explanation of that in docs
You can't start from an arbitrary place in a comprehension.
Instead, add a when condition that simply checks whether the index of the iteration is greater than the first element.
destroy c for c, i in container.children when i >= 1
Related
I was solving the problem Filter Positions in a List:(For a given list with integers, return a new list removing the elements at odd positions)
I came up with
arr.zipWithIndex.filter(_._2 %2 == 1).map(_._1)
But someone has suggested that below code would be faster
arr.view.zipWithIndex.filter{ _._2 % 2 != 0 }.map { _._1}.force.toList
I know, View creates unconditional collection(Lazies evaluation), But
at which step (Method call) it will help us.
Meaning:
arr.view, creates view on which zipWithIndex will work, and zipWithIndex will process each element to create Map of value and Index. I guess till now, no optimization.
filter method has to work on every element then it only it can skip or select it.
I am not sure, how adding view in this case would help.
Using view means that all the operations can happen at once, instead of one at a time.
arr.zipWithIndex.filter(_._2 %2 == 1).map(_._1)
This works, but it creates 3 new lists in the process, first it runs the zipWithIndex producing a new list with the result. Then passes than new list to the filter, creating another list, and finally calls map on that list producing the final list.
So in that we creates two intermediate lists that we don't really need.
arr.view.zipWithIndex.filter{ _._2 % 2 != 0 }.map { _._1}.force.toList
This version uses view so if can perform all those operations in one shot, without needing to create those intermediate collections at each step.
In q, a common illustration for the over operator / is the implementation of fibonacci sequence
10 {x,sum -2#x}/ 1 1
This indeed prints the first 10 fibonacci numbers but doesn't make sense in regards of the definition of the over operator in this whitepaper (page 8)
With two arguments, the second one being a list, the function is
called with the left argument as its first parameter and the first
element of the right argument as the second parameter. Next, the
function is called with the result of the previous iteration as the
first parameter and the third element as the second parameter. The
process continues in this way for the remaining elements of the list.
So in the fibonacci example above, at the first iteration the function would be called with [10;1] ("first parameter and first item of second parameter") which would already give an incorrect result.
My implementation is in line with the definition (and works)
1 1 {[l;c] l,sum -2#l}/til 10
but I don't like it because the parameter c is never used.
How can the first example be reconciled with the definition?
Thanks for the help
/ has a number of forms, described here: https://code.kx.com/q/ref/adverbs
The specific form being used here is "repeat" - https://code.kx.com/q/ref/adverbs/#converge-repeat
The fibonacci function here is monadic i.e. takes one parameter (x)
In this form, / will run the function with the supplied parameter (i.e. the list of 1 1), and then with the result of that call, and then again with the result of that call and so, until the number of iterations reaches 10 (the left argument to /)
The definition you provide is true if the function is a dyadic function (i.e. takes two parameters)
Hope this helps
Jonathon
AquaQ Analytics
The left argument is this example is being treated as an iteration integer atom (repeat).
Please see coverge-repeat on code.kx.com may add further clarification.
I'm using Scala, and have a ResultSet with an unknown number of elements. I'd like to loop through the set, processing each row, and end up with an array of the processed elements. The function rs.next() moves the pointer to the next element and returns true if that element is a meaningful row and false if that element is not (either after the last row, or the return was empty to begin with). So even though the following won't work, I'd like something structured like:
while (rs.next()) yield new foo(rs)
I tried the answer for this question, like so:
if (rs.next()) Iterator.continually(new foo(rs)).takeWhile(rs.next())
But this doesn't work because the element is created before the condition is checked, behaving as a do-while which has to process the first bad element. As written, it will create a foo using the last element of the resultset but not return it and requires the initial rs.next() to get started.
I have multiple other ways to approach this problem: another query to count the number of elements and then using take, using a boolean var that's set equal to rs.next() and then used to return a null element if false and also used for the takeWhile, a mutable collection that is added to in a while loop, and so on.
But I feel like I must be missing something, because some part of each of those solutions feels inelegant. Is there a simple functional construction that will repeatedly check a condition, creating an element to add to an iterator so long as the condition is true?
I need to return the first value in an array that is greater than another particular value. I have:
find(A > val, 1, 'first')
According to this post: https://stackoverflow.com/a/9464886/1985603 find is unavoidable in this case. But, what about:
B = A(A > val);
B(1)
Is there a good reason to use one over the other here, other than the extra line?
Yes there is; speed! Especially for large arrays, find will be significantly faster.
Think about it: the operation A > val is the same in both cases, but
B = A(A > val)
extracts values from A, and copies them into a new array B, which will have to be allocated and copy-assigned, and the A(A> val) temporary will have to be destroyed.
All find(A>val, 1, 'first') does is walk the list of logicals, and return a single number when it encounters the first true value; this is a lot less useless copying/assigning/etc., and therefore, much faster.
As a rule of thumb, when you don't use the additional options in find, logical indexing is almost always preferable. When you need or use find's additional functionalities, the find option is almost always preferable.
I'm learning Scala now, and I have a scenario where I have to compare an element (say num) with all the elements in a list.
Assume,
val MyList = List(1, 2, 3, 4)
If num is equal to anyone the elements in the list, I need to return true. I know to do it recursively using the head and tail functions, but is there a simpler way to it (I think I'll be able to do it using foreach, but I'm not sure how to implement it exactly)?
There is number of possibilities:
val x = 3
MyList.contains(x)
!MyList.forall(y => y != x) // early exit, basically the same as .contains
If you plan to do it frequently, you may consider to convert your list to Set, cause every .contains lookup on list in worst case is proportional to number of elements, whereas on Set it is effectively constant
val mySet = MyList.toSet
mySet.contains(x)
or simply:
mySet(x)
A contains method is pretty standard for lists in any language. Scala's List has it too:
http://www.scala-lang.org/api/current/scala/collection/immutable/List.html
As others have answered, the contains method on the list will do exactly this, and it's the most understandable/performant way.
Looking at your closing comments though, you wouldn't be able to do it (in an elegant fashion) with foreach, since that returns Unit. Foreach "does" something for each element, but you don't get any result back. It's useful for logging/println statements, but it doesn't act as a transformation.
If you want to run a function on every element individually, you would use map, which returns a List of the results of applying the function. So assuming num = 3, then MyList.map(_ == num) would return List(false, false, true, false). Since you're looking for a single result, and not a list of results, then this is not what you're after.
In order to collapse a sequence of things into a single result, you would use a fold over the data. Folding involves a function that takes two arguments (the result so far, and the current thing in the list) and returns the new running result. So that this can work on the very first element, you also need to provide the initial value to use for the ongoing result (usually some sort of zero).
In your particular case, then, you want a Boolean answer at the end - "was an element found that was equal to num". So the running result would be "have I seen an element so far that was equal to num". Which means the initial value is false. And the function itself should return true if an element has already been seen, or if the current element is equal to num.
Putting this together, it would look like this:
MyList.foldLeft(false) { case (runningResult, listElem) =>
// return true if runningResult is true, or if listElem is the target number
runningResult || listElem == num
}
This doesn't have the nice aspect of stopping as soon as the target value has been found - and it's nowhere near as concise as calling MyList.contains. But as an instructional example, this is how you could implement this yourself from the primitive functional operations on a list.
List has a method for that:
val found = MyList.contains(num)