Search code examples
nextflow

how to get first items in channel of tuples in Nextflow


Example:

#!/usr/bin/env nextflow
nextflow.enable.dsl=2

workflow 
{   
    days = Channel.of("Sat", "Sun", "Mon")
    tasks = Channel.of("Cleaning", "Cooking")    
    tasks_days = tasks.combine(days)
    tasks_days.view()

}

Current output:

$ nextflow run bench.nf 
N E X T F L O W  ~  version 22.04.0
Launching `bench.nf` [shrivelled_avogadro] DSL2 - revision: fb7c91b512
[Cleaning, Sat]
[Cooking, Sat]
[Cleaning, Sun]
[Cooking, Sun]
[Cleaning, Mon]
[Cooking, Mon]

I am interested in finding way to create new channel of tasks_days that contains the first element [Cleaning, Cooking, Cleaning, Cooking, Cleaning, Cooking]


Solution

  • You could use the map operator and a closure to do this:

    tasks_days = tasks.combine(days).map { it.first() }
    

    Note that the above will throw a NoSuchElementException given an empty list. If you'd prefer a null value when the list is empty, simply use:

    tasks_days = tasks.combine(days).map { it[0] }
    

    Note also that Groovy closures support argument unpacking, so in the simplest case you could just use the following to get the first element:

    tasks_days = tasks.combine(days).map { task, day -> task }