RequireJS recursive module loading - module

I have 2 modules A and B. Also I have 3 libs L1, L2 and L3.
Module A:
define(
['L1', 'L2'],
function (L1, L2) { ... }
);
Module B:
define(
['A', 'L3'],
function (A, L3) { ... }
);
Is i'm right that module B already have L1 and L2 libs in scope or I must reinclude these libs?
Module B:
define(
['A', 'L1', 'L2', 'L3'],
function (A, L1, L2, L3) { ... }
);

If you want to use those libs in Modulue B you have to explicitly name them in your definition.
define(['A', 'L1', 'L2', 'L3'], function (A, L1, L2, L3) {
// ...
});
If you don't want to use them this will be okay:
define(['A', 'L3'], function (A, L3) {
// L1 undefined here
});

Related

How to enumerate files in channel to use `collectFile`

I am trying to enumerate files in a Channel to rename them before using collectFile:
files.flatten().merge(Channel.fromList([1, 2, 3, 4])).collectFile(storeDir: "$SCRATCH/intermediate") {
item -> ["data${item[1]}.csv", item[0].text]
}
But the latest documentation says that the merge operator for channels is deprecated, but does not point to any alternative that should be used. What can I use instead of merge?
The migration notes say to use the join operator instead. If your inputs were lists, you could do something like:
def indexedChannel( items ) {
return Channel.from( items.withIndex() ).map { item, idx -> tuple( idx, item ) }
}
ch1 = indexedChannel( [ 15, 20, 21 ] )
ch2 = indexedChannel( [ 'a', 'b', 'c' ] )
ch3 = indexedChannel( [ 1, 2, 3 ] )
ch1
.join( ch2 )
.join( ch3 )
.view()
Results:
[0, 15, a, 1]
[1, 20, b, 2]
[2, 21, c, 3]
However, the merging/joining of two channels is unnecessary to enumerate. Just use the map operator:
def c = 1
Channel
.fromPath( './data/*.txt' )
.map { tuple( it, c++ ) }
.collectFile(storeDir: "$SCRATCH/intermediate") { fn, count ->
["data${count}.csv", fn.text]
}

zip with next value with kotlin Flow

how to zip a Flow with the next value as zipWithNext operator for collections?
zipWithNext behaves like:
val letters = ('a'..'f').toList()
val pairs = letters.zipWithNext()
println(letters) // [a, b, c, d, e, f]
println(pairs) // [(a, b), (b, c), (c, d), (d, e), (e, f)]
but in my case letters would be:
val letters = flowOf('a'..'f')
bonus points:
i tried flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() on https://play.kotlinlang.org/ but doesn't find flowOf what import or else i'm missing there?
One possible solution is:
val letters = ('a'..'f').toList().toTypedArray()
val lettersFlow = flowOf(*letters)
val result = lettersFlow.scan(Pair<Char, Char>('a','a')) { acc, value -> Pair(acc.second, value) }.drop(2).toList()
println(result)

How merge two list of objects and identify identical elements

I have 2 lists containing objects of the same type and I am looking to merge these 2 lists.
Let's take an example:
List1 contains [A, B, C, E]
List2 contains [A, D]
what I need [A, B, C, E, D]
I absolutely want the identical elements (here the object A) to be those of my list 1.
It does not matter if the order of the items is not kept.
If you want to keep identical elements from list1, you should not use distinct. Your code should be explicit on this business rule to avoid future errors.
An example :
class Elt(private val id: Int, private val content: String) {
open fun equals(other: Elt): Boolean {
return this.id == other.id
}
override fun toString(): String {
return "$id -> $content"
}
}
fun main(args: Array<String>) {
val l1 = listOf(Elt(1,"L1"), Elt(2,"L1"), Elt(3,"L1"), Elt(4,"L1"))
val l2 = listOf(Elt(1,"L2"), Elt(5,"L2"))
val l4 = l2 + l1
println(l4.distinct()) // Elt 1 comes from L2
val l5 = l1 + l2
println(l5.distinct()) // Elt 1 comes from L1
val l6 = l2.toMutableList().apply { addAll(l1) }.distinct()
println(l6.distinct()) // Elt 1 comes from L2
}
It will print:
[1 -> L1, 2 -> L1, 3 -> L1, 4 -> L1, 1 -> L2, 5 -> L2]
[1 -> L2, 5 -> L2, 1 -> L1, 2 -> L1, 3 -> L1, 4 -> L1]
[1 -> L1, 2 -> L1, 3 -> L1, 4 -> L1, 1 -> L2, 5 -> L2]
[1 -> L2, 5 -> L2, 1 -> L1, 2 -> L1, 3 -> L1, 4 -> L1]
If you remove duplicate in list2 before adding the elements, you will ensure that you keep identical ielement from list1:
val l3 = l1 + (l2 - l1.intersect(l2))
println(l3)
Simple case:
val lista = listOf( 1,2,3 )
val listb = mutableListOf( 1,4,5 ).apply { addAll(lista) }.distinct()
// result listb -> [1, 4, 5, 2, 3]
To add two string list
val a = listOf("a","b" ,"c" , "e")
val b = listOf("a", "d")
val c = a + b
To have only distinct values,
val d = c.distinct()
An alternative to the above solutions: use HashSet. Set collections don't support multiple occurrences of the same element so when you add A twice, the second one simply gets discarded.
var s: HashSet<String> = HashSet<String>()
s.addAll(listOf("A", "B", "C", "E"))
s.addAll(listOf("A", "D"))
var l = s.toList()
Since HashSet uses hashing under the hood, you get O(1) complexity on most of its operations.

How to iterate over the product of several ranges or iterators?

Is there a natural way in Rust to iterate over the "product" of several ranges or iterators?
This comes up when you're iterating over a multidimensional array, or perhaps some state space. For instance, I want to consider all possible values of a boolean tuple with 5 elements. Nesting 5 for loops is a bit unwieldy.
Here is a macro that does the job:
macro_rules! product {
($first:ident, $($next:ident),*) => (
$first.iter() $(
.flat_map(|e| std::iter::repeat(e)
.zip($next.iter()))
)*
);
}
fn main() {
let a = ['A', 'B', 'C'];
let b = [1, 4];
let c = [true, false];
let d = ['x', 'y'];
for (((a, b), c), d) in product![a, b, c, d] {
println!("{} {} {} {}", a, b, c, d);
}
}
Output:
A 1 true x
A 1 true y
A 1 false x
A 1 false y
A 4 true x
A 4 true y
etc...
Playpen example
The macro expands to the following
a.iter()
.flat_map(|e| std::iter::repeat(e).zip(b.iter()))
.flat_map(|e| std::iter::repeat(e).zip(c.iter()))
.flat_map(|e| std::iter::repeat(e).zip(d.iter()))
flat_map(|e| ... ) combines a sequence of iterators into an iterator. The e is an element yielded by an iterator.
std::iter::repeat(e) creates an iterator that repeats e.
.zip( ... ) iterates over two iterators simultaneously, yielding the elements of both as a pair.
Macros are a bit longer to explain, so it's best to read the macro chapter in the book
The itertools crate has a very ergonomic macro (iproduct!) for iterating over the product of iterators. Here is an example:
pub fn main() {
let a = ['A', 'B', 'C'];
let b = [1, 4];
let c = [true, false];
let d = ['x', 'y'];
for (a, b, c, d) in itertools::iproduct!(&a, &b, &c, &d) {
println!("{} {} {} {}", a, b, c, d);
}
}

Dynamically build list comprehension in Haskell

I am curious if it is possible to dynamically build a list comprehension in Haskell.
As an example, if I have the following:
all_pows (a,a') (b,b') = [ a^y * b^z | y <- take a' [0..], z <- take b' [0..] ]
I get what I am after
*Main> List.sort $ all_pows (2,3) (5,3)
[1,2,4,5,10,20,25,50,100]
However, what I'd really like is to have something like
all_pows [(Int,Int)] -> [Integer]
So that I can support N pairs of arguments without building N versions of all_pows. I'm still pretty new to Haskell so I may have overlooked something obvious. Is this even possible?
The magic of the list monad:
ghci> let powers (a, b) = [a ^ n | n <- [0 .. b-1]]
ghci> powers (2, 3)
[1,2,4]
ghci> map powers [(2, 3), (5, 3)]
[[1,2,4],[1,5,25]]
ghci> sequence it
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> mapM powers [(2, 3), (5, 3)]
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> map product it
[1,5,25,2,10,50,4,20,100]
ghci> let allPowers list = map product $ mapM powers list
ghci> allPowers [(2, 3), (5, 3)]
[1,5,25,2,10,50,4,20,100]
This probably deserves a bit more explanation.
You could have written your own
cartesianProduct :: [[a]] -> [[a]]
cartesianProduct [] = [[]]
cartesianProduct (list:lists)
= [ (x:xs) | x <- list, xs <- cartesianProduct lists ]
such that cartesianProduct [[1],[2,3],[4,5,6]] ⇒ [[1,2,4],[1,2,5],[1,2,6],[1,3,4],[1,3,5],[1,3,6]].
However, comprehensions and monads are intentionally similar. The standard Prelude has sequence :: Monad m => [m a] -> m [a], and when m is the list monad [], it actually does exactly what we wrote above.
As another shortcut, mapM :: Monad m => (a -> m b) -> [a] -> m [b] is simply a composition of sequence and map.
For each inner list of varying powers of each base, you want to multiply them to a single number. You could write this recursively
product list = product' 1 list
where product' accum [] = accum
product' accum (x:xs)
= let accum' = accum * x
in accum' `seq` product' accum' xs
or using a fold
import Data.List
product list = foldl' (*) 1 list
but actually, product :: Num a => [a] -> a is already defined! I love this language ☺☺☺