Does Kotlin have an "enumerate" function like Python? - list

In Python I can write:
for i, element in enumerate(my_list):
print(i) # the index, starting from 0
print(element) # the list-element
How can I write this in Kotlin?

Iterations in Kotlin: Some Alternatives
Like already said, forEachIndexed is a good way to iterate.
Alternative 1
The extension function withIndex, defined for Iterable types, can be used in for-each:
val ints = arrayListOf(1, 2, 3, 4, 5)
for ((i, e) in ints.withIndex()) {
println("$i: $e")
}
Alternative 2
The extension property indices is available for Collection, Array etc., which let's you iterate like in a common for loop as known from C, Java etc:
for(i in ints.indices){
println("$i: ${ints[i]}")
}

There is a forEachIndexed function in the standard library:
myList.forEachIndexed { i, element ->
println(i)
println(element)
}
See #s1m0nw1's answer as well, withIndex is also a really nice way to iterate through an Iterable.

Related

Creating a List Specification in Alloy Language

I'm working on defining a List in Alloy but I'm stuck.
This is what I have so far (it acts like a LinkedList):
module List
// The List signature
lone sig List { rootElement: lone Element }
// A list element signature
sig Element { nextElement: lone Element }
// Prevents an Element from referencing itself
fact preventElementLooping {
no ele: Element | ele = ele.nextElement
}
// Zero Element outliers
fact allElementsBelongToOneList {
all ele: Element | one list: List | ele in list.rootElement.*nextElement
}
// Prevents Elements from referencing a Element before it in the List
fact preventCycle {
no ele: Element | ele in ele.^nextElement
}
This all looks good to me and I feel like this is correct.
I'm trying to define 3 predicates for this list definition:
Create: Should create an empty list
Put: Should add an item to the end of the list
Find: Should return all indices in the list that match a given element
pred create(list, list":List) {
list".rootElement = none
}
pred put(list, list":List, ele: Element) {
list".rootElement = ele
}
pred find [list:List, ele: Element] {
ele = list.rootElement or ele in list.rootElement.^nextElement
}
This is what I need help with I feel like I'm missing something in those 3 preds.
My questions:
Am I over complicating things by trying to use a linked list? How would you just do a normal list?
Put is correct for the first put but fails when you need to put again as it just replaces the root element
Find is the big struggle. I need to store the indices somewhere to return them right? Also I thought alloy only had bare bones understanding of Numbers for indexes (I believe only allowing -7 to 8). Should index be its own signature?
Thanks in advance
There are several ways to define a notion of list in Alloy, yours is a possibility, depending no what you expect to do then.
I don't see why you want to make List a lone sig?
Another remark is that your list doesn't contain any data, only "elements" (I would call them cells), perhaps because it's of no use in your spec? Anyhow, you could make your module generic and store data in cells, e.g.:
module List[Data]
sig List { rootElement: lone Element }
sig Element { data: one Data, nextElement: lone Element }
Your facts can also be improved:
By having only one fact rejecting all forms of cycles.
By only asking for elements to belong to some list rather than exactly one.
Finally, regarding operations, I suggest you take a look at how the standard library models lists and operations:
util/seqrel specifies lists as relations
util/sequence specifies lists as signatures holding elements
util/sequniv is like util/seqrel but relies on builtin integer indices and is implemented in an ad hoc concrete syntax based on the seq keyword.

In Rust, how do you create a slice that is backed by a tuple?

Suppose I have some tuple on the stack:
let a:(u8,u8,u8) = (1,2,3);
How do I create a slice into all, or some of a?
Rust reference defines tuples as having contiguous layout and defined order, so you can take a pointer to the first element of a tuple and transform it to a slice:
#![feature(tuple_indexing)]
use std::slice;
fn main() {
let t = (1u8, 2u8, 3u8);
let f: *const u8 = &t.0;
let s = unsafe { slice::from_raw_buf(&f, 3) };
println!("{}", s); // [1, 2, 3]
}
There is also this RFC but it was closed quite some time ago.
In most cases it doesn't make sense to do this. The main distinction between a tuple and a fixed size array of the same size is that the tuple supports heterogeneous elements, while arrays contain elements of the same type. Slices are fat pointers to an array of values of the ~same type that are consecutive in memory, so while they might make sense for ~some tuples, they don't in general, and therefore slice operations are not supported on tuples.

Returning elements of a row in a list using Scala

I need to write a method that will return the contents of a particular row (index of it is inputted as method parameter). I have to use recursion and no loops.
So far I have attempted this uncompleted code (and I have no idea how to continue it):
class Sudoku(val grid: List[List[Int]]) {
def r(r: Int): Set[Int] = {
if (grid.isEmpty) Set()
else
}
}
I also do not know how Set works. Any help would be really appreciated. PS: I am not asking for complete code, an algorithm explanation would be more than enough!
This is the answer to the literal interpretation of the question:
class Sudoku(val grid: List[List[Int]]) {
def row(n: Int): List[Int] =
if (grid.size > n) grid(n) else Nil
}
The apply method on List, here applied on the value grid, which can be written either grid apply n, or simply grid(n) returns the n'th element of the list. If that element does not exist (e.g. grid(1000000)), it throws an exception, therefore we check the size of the list first.
I have no idea why you should return a Set, but you could simple call .toSet on the result. A Set is a collection with distinct elements (each element only occurs once) with no guarantee of ordering.
I also don't know why you would need recursion for this, so I reckon the question is part of a larger problem.

Removing all occurrences of a given value from an array in D

Suppose that I have an array. I want to remove all the elements within the array that have a given value. Does anyone know how to do this? The value I am trying to remove may occur more than once and the array is not necessarily sorted. I would prefer to filter the array in-place instead of creating a new array. For example, removing the value 2 from the array [1, 2, 3, 2, 4] should produce the result [1, 3, 4].
This is the best thing I could come up with:
T[] without(T)(T[] stuff, T thingToExclude) {
auto length = stuff.length;
T[] result;
foreach (thing; stuff) {
if (thing != thingToExclude) {
result ~= thing;
}
}
return result;
}
stuff = stuff.without(thingToExclude);
writeln(stuff);
This seems unnecessarily complex and inefficient. Is there a simpler way? I looked at the std.algorithm module in the standard library hoping to find something helpful but everything that looked like it would do what I wanted was problematic. Here are some examples of things I tried that didn't work:
import std.stdio, std.algorithm, std.conv;
auto stuff = [1, 2, 3, 2, 4];
auto thingToExclude = 2;
/* Works fine with a hard-coded constant but compiler throws an error when
given a value unknowable by the compiler:
variable thingToExclude cannot be read at compile time */
stuff = filter!("a != " ~ to!string(thingToExclude))(stuff);
writeln(stuff);
/* Works fine if I pass the result directly to writeln but compiler throws
an error if I try assigning it to a variable such as stuff:
cannot implicitly convert expression (filter(stuff)) of type FilterResult!(__lambda2,int[]) to int[] */
stuff = filter!((a) { return a != thingToExclude; })(stuff);
writeln(stuff);
/* Mysterious error from compiler:
template to(A...) if (!isRawStaticArray!(A)) cannot be sliced with [] */
stuff = to!int[](filter!((a) { return a != thingToExclude; })(stuff));
writeln(stuff);
So, how can I remove all occurrences of a value from an array without knowing the indexes where they appear?
std.algorithm.filter is pretty close to what you want: your second try is good.
You'll want to either assign it to a new variable or use the array() function on it.
auto stuffWithoutThing = filter!((a) { return a != thingToExclude; })(stuff);
// use stuffWithoutThing
or
stuff = array(filter!((a) { return a != thingToExclude; })(stuff));
The first one does NOT create a new array. It just provides iteration over the thing with the given thing filtered out.
The second one will allocate memory for a new array to hold the content. You must import the std.array module for it to work.
Look up function remove in http://dlang.org/phobos/std_algorithm.html. There are two strategies - stable and unstable depending on whether you want the remaining elements to keep their relative positions. Both strategies operate in place and have O(n) complexity. The unstable version does fewer writes.
if you want to remove the values you can use remove
auto stuffWithoutThing = remove!((a) { return a == thingToExclude; })(stuff);
this will not allocate a new array but work in place, note that the stuff range needs to be mutable

how to make more expressive python iterators? just like c++ iterator

Firstly, I review the c++ style iterators quickly.for example:
//--- Iterating over vector with iterator.
vector<int> v;
. . .
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
cout << *it << endl;
}
It is flexible. It is easily to change underlying container types. For example, you might decide later that the number of insertions and deletions is so high that a list would be more efficient than a vector. It also has many useful member functions. Many of the member functions for vector use iterators, for example, assign, insert, or erase. Moreover, we can use iterator (if supported) bidirectionaly, such as ++, --. This is useful to parse a stream like objects.
The problems of python is:
1:Currently, python for loop syntax is less flexible than c++ for. (well , safer)
2:rather than "it != iter.end()" style, python will throw exception when next() has no more. It is not flexible.
Question 1: Is my idea above correct?
OK. Here comes my question, how to implement a more powerful python iterator as powerful as c++ iterators? Currently, python for loop syntax is less flexible than c++ for. I also find some possible solutions, such as http://www.velocityreviews.com/forums/t684406-pushback-iterator.html. but it asks user to push_back a stuff rather than ask iterator --.
Question 2: What is the best to implement a Bidirectional Iterator in python? Just like http://www.cplusplus.com/reference/std/iterator/BidirectionalIterator/.
The pseudo-code is the following:
it = v.begin();
while( it!=v.end()) {
//do sth here
if (condition1)
++it;//suppose this iterator supports ++
if(condition2)
--it;//suppose this iterator supports --
}
The key features are: 1) bidirectional , 2) simpler "end" checking. The "++" or "--" operators or common functions do not matter (it has no semantic difference anyway).
Thanks,
Update:
I got some possible solutions from the answers:
i = 0
while i < len(sequence): # or i < len and some_other_condition
star_it = sequence[i]
if condition_one(star_it):
i += 1
if condition_two(star_it):
i = max(i - 1, 0)
However, unlike array, random access of list should be O(n). I suppose the "list" object in python internally is implemented using linked-list like stuff. Thus, this while loop solution is not efficient. However, in c++, we have "random iterator", "bidirectional iterator". How should I get a better solution? Thanks.
For the majority of situations, Python's for and iterators are the simplest thing around. That is their goal and they shouldn't compromise it for flexibility -- their lack of flexibility isn't a problem.
For a few situations where you couldn't use a for loop, C++ iterators might be simpler. But there is always a way to do it in Python that isn't much more complex than using a C++ iterator.
If you need to separate advancing the iterator from looping, just use a while loop:
it = iter(obj)
try:
while True: # or some secondary break condition other than StopIteration
star_it = next(it)
if condition_one(star_it):
star_it = next(it)
except StopIteration:
pass # exhausted the iterator
I can think of only two situations where --it makes sense in Python.
The first is you're iterating over a sequence. In that case, if you need to go backwards, don't use an iterator at all -- just use a counter with a while loop:
i = 0
while i < len(sequence): # or i < len and some_other_condition
star_it = sequence[i]
if condition_one(star_it):
i += 1
if condition_two(star_it):
i = max(i - 1, 0)
The second is if you're iterating over a doubly linked list. In that case, again, don't use an iterator -- just traverse the nodes normally:
current = node
while current: # or any break condition
if condition_one(current):
current = current.next
if condition_two(star_it):
current = current.prev
A situation where you might think it makes sense, but you can't use either of the above methods, is with an unordered collection like a set or dict. However, --it doesn't make sense in that case. As the collection is unordered, semantically, any of the items previously reached would be appropriate -- not just the actual previous item.
So, in order to know the right object to go back to, you need memory, either by iterating over a sequence like mydict.values() or tuple(myset) and using a counter, or by assembling a sequence of previous values as you go and using a while loop and next as above instead of a for loop.
Solutions for a few situations you mentioned:
You want to replace objects in the underlying container. For dictionaries, iterate over the keys or items, not only the values:
for key, value in my_dict.iteritems():
if conditiion(value):
my_dict[key] = new_value
For lists use enumerate():
for index, item in enumerate(my_list):
if condition(item):
my_list[index] = new_item
You want an iterator with one "look-ahead" value. You probably would use something tailored to a specific situation, but here's a recipe for general situations:
def iter_with look_ahead(iterable, sentinel=None):
iterable, it_ahead = itertools.tee(iterable)
next(it_ahead, None)
return izip_longest(iterable, it_ahead, fillvalue=sentinel)
for current, look_ahead in iter_with look_ahead(tokens):
# whatever
You want to iterate in reverse. Use reversed() for containers that support it.
You want random access. Just turn your iterable into a list and use indices:
my_list = list(my_iterable)
Actually, C++ iterator system is not so great. Iterators are akin to pointers, and they have their woes:
singular values: v.end() cannot be dereferenced safely
inversion issues: std::for_each(end, begin, func);
mismatch issues: std::for_each(v0.begin(), v2.end(), func);
Python approach is much better in this regard (though the use of exception can be quite surprising at first, it really helps defining nested iterators), because contrary to its name, a Python iterator is more akin to a Range.
The concept of Range is so much better than C++11 introduces the range-for loop construct:
for (Object& o: range) {
}
Anything that is possible with an iterator is also possible with a range, though it may take some times to realize it and some translations seem surrealists at first for those of us who were educated with C++ pointer-like iterators. For example, subranges can perfectly be expressed:
for (Object& o: slice(range, 2, 9)) {
}
where slice would take all elements in position [2, 9) within range.
So, instead of fighting your language (Python) you should delve further into it and embrace its style. Fighting against a language is generally a losing battle, learn its idioms, become efficient.
You could implement a similar way of C++ using python objects:
class Iterable(object):
class Iterator(object):
def __init__(self, father, pos=0):
self.father = father
self.pos = pos
def __getitem__(self, pos=0):
return self.father[self.pos + pos]
def __setitem__(self, pos, value):
self.father[self.pos + pos] = value
def __iadd__(self, increment):
self.pos += increment
return self
def __isub__(self, decrement):
self.pos -= decrement
return self
def __ne__(self, other):
return self.father != other.father or self.pos != other.pos
def __eq__(self, other):
return not (self != other)
def begin(self):
return self.Iterator(self)
def end(self):
return self.Iterator(self, len(self))
class Vector(list, Iterable):
pass
v = Vector([54, 43, 32, 21])
counter = 0
it = v.begin()
print it, it[0]
while it != v.end():
counter += 1
print it[0]
if counter == 2:
it += 1; # suppose this iterator supports ++
if counter == 1:
it -= 1; # suppose this iterator supports --
it += 1
This replaces *it by it[0] (also analog to C++) and it++ by it += 1, but in effect it stays pretty much the same.
You leave the Pythonic ways if you do this, though ;-)
Note that the list object in Python is an array, so the efficiency concern mentioned in the question is actually a non-issue.