Iterate over pairs in a list (circular fashion) in Python
def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first Works on any non-empty sequence, no indexing required.
def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first Works on any non-empty sequence, no indexing required.
it’s typically referred to as flattening a nested structure. >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> [element for tupl in tupleOfTuples for element in tupl] [1, 2, 3, 4, 5] Just to demonstrate efficiency: >>> import timeit >>> it = lambda: list(chain(*tupleOfTuples)) >>> timeit.timeit(it) 2.1475738355700913 >>> lc = lambda: [element for tupl in … Read more
Question: Why doesn’t the same piecewise constructibility exist for arrays and tuples? My recollection is that piecewise construction was added to std::pair for one reason only: to support uses-allocator construction of the pair elements, i.e. to allow an allocator to be provided and conditionally passed to the elements if they support construction with an allocator … Read more
This isn’t simply “multiple variable assignment”, it’s fully-featured pattern matching! So the following are all valid: val (a, b) = (1, 2) val Array(a, b) = Array(1, 2) val h :: t = List(1, 2) val List(a, Some(b)) = List(1, Option(2)) This is the way that pattern matching works, it’ll de-construct something into smaller parts, … Read more
You can just do (a,). No need to use a function. (Note that the comma is necessary.) Essentially, tuple(a) means to make a tuple of the contents of a, not a tuple consisting of just a itself. The “contents” of a string (what you get when you iterate over it) are its characters, which is … Read more
Classic Example: You want to store point value as tuple of (x, y)
Yes. It’s called a tuple. So, instead of [1,2] which is a list and which can be mutated, (1,2) is a tuple and cannot. Further Information: A one-element tuple cannot be instantiated by writing (1), instead, you need to write (1,). This is because the interpreter has various other uses for parentheses. You can also … Read more
Addressing questions one to three: one of the main applications for HLists is abstracting over arity. Arity is typically statically known at any given use site of an abstraction, but varies from site to site. Take this, from shapeless’s examples, def flatten[T <: Product, L <: HList](t : T) (implicit hl : HListerAux[T, L], flatten … Read more
What about: [ (x,y) | (x:rest) <- tails xs , y <- rest ]
It looks to me like resultArray.append() is treating the tuple a little bit like a variadic parameter, and trying to expand the tuple to match its own arguments. It’s complaining about your second parameter because it’s only expecting one. I haven’t seen this behavior for Array.append() documented anywhere, so I would say it’s a bug … Read more