as defined here:
Module.init is implemented like:
Module.init = Controller.init = Model.init = (a1, a2, a3, a4, a5) ->
new this(a1, a2, a3, a4, a5)
why is it like this? why define 5 attributes and not use attrs... so attributes are not fixed to 5....
new this(attrs...)
Maybe it's because the compiled JS is much smaller (Spine.js makes a lot of emphasis on low footprint).
Module.init = Controller.init = Model.init = (a1, a2, a3, a4, a5) ->
new this(a1, a2, a3, a4, a5)
Compiles to:
Module.init = Controller.init = Model.init = function(a1, a2, a3, a4, a5) {
return new this(a1, a2, a3, a4, a5);
};
While:
Module.init = Controller.init = Model.init = (args...) ->
new this args...
Compiles to the much more convoluted:
var __slice = [].slice;
Module.init = Controller.init = Model.init = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args), t = typeof result;
return t == "object" || t == "function" ? result || child : child;
})(this, args, function(){});
};
This is because in JavaScript the new operator and apply cannot be used in conjunction :(
Either someone didn't know about splats, or they felt that it was cleaner to do it this way, or maybe they were thought it would be more performant to not use a bunch of extra logic to process the arguments object.
Related
Let's say I have two modules M1 and M2 and both of them are outputting 32 bits data. I would like to do logic AND for each bit. How to do it?
I have been looking into Library on GitHub but couldn't find module for AND operation.
I would like to do next:
X[0] = M1[0] && M2[0]
X[1] = M1[1] && M2[1]
etc.
Code example of add_gate:
#gear
async def and_gate(arg1, arg2) -> (Uint[32]):
async with arg1 as a1:
async with arg2 as a2:
res = a1 & a2
yield res
#alternative(and_gate)
#gear
async def and_gate_one_arg(args) -> (Uint[32]):
async with args as (a1, a2):
res = a1 & a2
yield res
res_two = []
res_one = []
#gear
def consumer():
arg1 = once(val=31, tout=Uint[32])
arg2 = once(val=15, tout=Uint[32])
args = once(val=(15, 31), tout=Tuple[Uint[32], Uint[32]])
bits_and_two_args = and_gate(arg1, arg2)
bits_and_one_arg = and_gate(args)
collect(bits_and_two_args, result=res_two)
collect(bits_and_one_arg, result=res_one)
consumer()
sim()
print(res_one)
print(res_two)
How it represents in GearBox:
I have the following list of objects:-
case class Account(id: Long, locked: Boolean)
val a1 = Account(1, false)
val a2 = Account(2, false)
val a3 = Account(3, true)
val a4 = Account(4, true)
val accounts = List(a1, a2, a3, a4)
And here is a method which is working correctly.
def getAccounts(includeLocked: Boolean): List[Account] = {
if(includeLocked) {
accounts.filter(acc => acc.locked == false)
} else {
accounts
}
}
Invoking getAccounts(false) correctly filters out locked Accounts and getAccounts(false) returns everything which is what I want.
getAccounts(false)
List(Account(1,false), Account(2,false))
getAccounts(true)
List(Account(1,false), Account(2,false), Account(3,true), Account(4,true))
But is there a more idiomatic way of implementing getAccounts?
My current if(includeLocked) approach feels rather clunky.
As commented by others, it looks like if(includeLocked) should be if(!includeLocked) in your sample code.
A more concise version could be like the following:
def getAccounts(includeLocked: Boolean): List[Account] =
accounts.filter(acc => includeLocked || !acc.locked)
getAccounts(true)
// res1: List[Account] = List(Account(1,false), Account(2,false), Account(3,true), Account(4,true))
getAccounts(false)
// res2: List[Account] = List(Account(1,false), Account(2,false))
Note that if/else (or pattern match) might be more verbose, it's probably more intuitive to read though.
I am trying to produce a function that involves a unique initiating object, a target object and a path object, in which the initiating and target objects are of the same class A, and the path object is of a different class B. The ideal output of this specific function should be input A1, A2 to B1; however, the result is input , to B1:
import UIKit
var interA = ""
var interB = ""
class A {
//Where any unique unit in A must interact with any other unique unit in A through a unique path B.
var name = "name"
}
class B {
var path = "path"
}
func action(user: A, medium: B, target: A) {
interA = user.name
interB = target.name
print(medium.path)
}
var A1 = A()
A1.name = "A1"
var A2 = A()
A2.name = "A2"
var B1 = B()
B1.path = "input \(interA), \(interB) to B1" //String simplification of multivariate function f(AI, AJ)
action(user: A1, medium: B1, target: A2) //Should show up as "input A1, A2 to B1"
Any solutions to the problem or more simplified methods of approach are appreciated. (Future inputs to this function should ideally include all the possible permutations of AI, AJ and BK for positive integers I, J and K.)
You are setting the path variable before action has a chance to update the user/target values. The replacement of the "\()" values happens once when the string is evaluated, not dynamically.
I have one interesting question. Maybe anybody know how could I implement a method like a http://ramdajs.com/docs/#xprod. I have one solution which I found:
let as = [1, 2, 3];
let bs = ['a', 'b', 'c'];
Rx.Observable.for(bs, b => {
return Rx.Observable.for(as, a => Rx.Observable.just([a, b]));
}).toArray().subscribe(x => {
console.log(x.sort((a, b) => a[0] - b[0]));
});
I agree with Ben Lesh's comment above that, unless there's something async going on, you probably don't need to use an Observable.
A plain ES5, array-based solution (which is equivalent to Matt Podwysocki's inner map solution) could look like:
var as = [1, 2, 3],
bs = ['a', 'b', 'c'];
as.flatMap = flatMap;
var product = as.flatMap(pairWithAllBs);
// pairWithAllBs :: Number -> [[Number, String]]
function pairWithAllBs(a) {
return bs.map(function (b) {
return [a, b];
});
}
// flatMap :: #[a], (a -> [b]) -> [b]
// JS does not have a built-in flatMap function.
function flatMap(fn) {
return Array.prototype.concat.apply([], this.map(fn));
}
In ES7, using array comprehensions, we should be able to just do:
[for (a of as) for (b of bs) [a, b]];
Updated question:
In my original question I did not know how to refer to the following problem. To clarify my question, I added the following illustration from Wikipedia:
It turns out that the problem is also named after this analogy: Riffle shuffle permutations. Based on this terminology my question simply becomes: How can I iterate/enumerate all riffle shuffle permutations in the general case of multiple decks?
Original question:
Let's assume we are given multiple sequences and we want to merge these sequences into one single sequence. The resulting sequence should preserve the order of the original sequences. Think of merging multiple stacks of cards (say Seq[Seq[T]]) into one single stack (Seq[T]) by randomly drawing a card from any (random) stack. All input stacks should be fully merged into the resulting stack. How can I iterate or enumerate all possible compositions of such a resulting sequence?
To clarify: If I have three stacks A, B, C (of say 5 elements each) then I do not only want the six possible arrangements of these stacks like "all of A, all of B, all of C" and "all of A, all of C, all of B" etc. I rather want all possible compositions like "1. of A, 1. of B, 2. of A, 1. of C, 3. of A, 2. of B, ...".
Since I'm a bit under the weather today, my first approach is terribly ugly and also produces duplicates:
def enumerateCompositions[T](stacks: Seq[Seq[T]], prefix: Seq[T]): Seq[Seq[T]] = {
if (stacks.length == 0) return {
Seq(prefix)
}
stacks.zipWithIndex.flatMap{ case (stack, stackInd) =>
if (stack.length > 0) {
val stacksWithHeadRemoved = stacks.indices.map{ i =>
if (i != stackInd) stacks(i) else stacks(i).drop(1)
}
enumerateCompositions(stacksWithHeadRemoved, prefix :+ stack.head)
} else {
val remainingStacks = stacks.indices.filterNot(_ == stackInd).map(i => stacks(i))
enumerateCompositions(remainingStacks, prefix)
}
}
}
Any idea how to make this more elegant and get rid of the duplicates?
Let's call this operation "to riffle". Here is a clean idomatic solution:
def allRiffles[T](stack1: List[T], stack2: List[T]): List[List[T]] =
(stack1, stack2) match {
case (x :: xs, y :: ys) => {
allRiffles(xs, stack2).map(x :: _) ++
allRiffles(stack1, ys).map(y :: _)
}
case _ => List(stack1 ++ stack2) // at least one is empty
}
def allRifflesSeq[T](stacks: Seq[List[T]]): List[List[T]] =
stacks.foldLeft(List(List[T]())) { (z, x) =>
z.flatMap(y => allRiffles(y, x))
}
allRiffles will produce all the possible rifflings of two stacks. allRifflesSeq will take a sequence of stacks and produce all the possible rifflings using a fold. For example, if allRifflesSeq is given stacks A, B, and C, it first produces all possible rifflings of A and B and then riffles C into each of those rifflings.
Note that allRiffles consumes stacks space proportional to the length of the shortest stack and allRifflesSeq consumes stacks space bounded by the length of the longest stack. Also, the returned list could be huge (combinatoric explosion) and consume a lot of heap space. An Iterator based solution is safer, but much less pretty:
def allRiffles[T](stacks: List[List[T]]): Iterator[List[T]] = new Iterator[List[T]] {
type Frame = (List[List[T]], List[List[T]], List[T])
var stack = List[Frame]((Nil, stacks, Nil))
var ready = false
var cachedHasNext: Boolean = _
var cachedNext: List[T] = _
def computeNext: Unit = {
while (stack.nonEmpty) {
val (doneStacks, stacks, prefix) :: stackTail = stack
stack = stackTail
stacks match {
case Nil => {
cachedNext = prefix.reverse
cachedHasNext = true
return
}
case Nil :: rest =>
stack ::= (doneStacks, rest, prefix)
case (xs#(x :: xtail)) :: rest =>
if (rest.nonEmpty)
stack ::= (xs :: doneStacks, rest, prefix)
val newStacks = doneStacks.reverse ++ (if (xtail.isEmpty) rest
else xtail :: rest)
stack ::= (Nil, newStacks, x :: prefix)
}
}
cachedHasNext = false
}
def ensureReady = {
if (!ready) {
computeNext
ready = true
}
}
def next = {
ensureReady
if (cachedHasNext) {
val next = cachedNext
ready = false
next
} else Iterator.empty.next
}
def hasNext = {
ensureReady
cachedHasNext
}
}
I have written this in Java. The code is following.
import java.util.*;
import java.io.*;
public class RiffleShufflePermutation {
protected static ArrayList<String> a1 = null;
protected static ArrayList<String> a2 = null;
protected static ArrayList<ArrayList<String>> a = new <ArrayList<ArrayList<String>>();
private static int getStartingPosition(ArrayList<String> inA, String inS) {
for(String s : inA)
if (s.equals(inS))
return inA.indexOf(s)+1;
return 0;
}
private static void shootRiffle(int previous, int current) {
ArrayList<ArrayList<String>> newAA = new ArrayList<ArrayList<String>>();
ArrayList<String> newA;
int start;
for(ArrayList<String> al : a) {
start = (previous < 0)?0:getStartingPosition(al,a2.get(previous));
for(int i=start; i<=al.size(); i++) {
newA = new ArrayList<String>();
newA.addAll(al);
newA.add(i,a2.get(current));
newAA.add(newA);
}
}
a.clear();
a.addAll(newAA);
}
public static void main(String[] args) {
a1 = new ArrayList(Arrays.asList("a1","a2","a3"));
a2 = new ArrayList(Arrays.asList("b1","b2"));
a.add(a1);
for (int i=0; i<a2.size(); i++)
shootRiffle(i-1,i);
int i = 0;
for (ArrayList<String> s : a)
System.out.println(String.format("%2d",++i)+":"+s);
}
}
Here is the Output:
1:[b1, b2, a1, a2, a3]
2:[b1, a1, b2, a2, a3]
3:[b1, a1, a2, b2, a3]
4:[b1, a1, a2, a3, b2]
5:[a1, b1, b2, a2, a3]
6:[a1, b1, a2, b2, a3]
7:[a1, b1, a2, a3, b2]
8:[a1, a2, b1, b2, a3]
9:[a1, a2, b1, a3, b2]
10:[a1, a2, a3, b1, b2]
Hopefully this is useful.