I came across this bit of code:
n = args[0] as Long
[*n..1, n].any{ println ' '*it + '*'*(n - ~n - it*2) }
It’s used for printing a tree form of structure. Like this:
*
***
*****
*******
*
(for n=4)
-
How does the code
[*n..1,n]produce[4, 3, 2, 1, 4]? -
How does
anymethod works here? The Doc doesn’t help me much. What is a predictive that can be passed toany(as mentioned in Doc‘s)?
Whats the use of any and how its handled in this case?
Q1a:
*“unpacks” an array...creates a range.[]creates a collection.Q1b:
*n..1unpacks [4,3,2,1] into its individual parts.Q1c:
[4,3,2,1,n]==[4,3,2,1,4]Q2: I don’t know why
anywas used here;eachworks just as well, and makes more sense in context.anydoes loop over the connection, so theprintlnside-effect functions as intended.Normally
anywould be used to determine if any collection elements met a criteria, for example:The last statement of the closure is used to determine if each item meets the criteria.
printlnreturns null, soanywill return false. The value is unused and discarded.The only reason I can think of that someone might have used
anyis to avoid seeing the return value ofeachin the console.eachreturns the original collection.