Quick actions

cmd+k|ctrl+k

Navigation

Languages

Raku-oFun-Feature-Demonstration-Using-Quick-Sort

Snippet info

Language

Raku

Visibility

public

Author

221a86612c7785cb6094f25b034cba9994736288

Created

2025-11-13T08:12:23.864567Z

Updated

2025-11-13T09:53:26.577293Z

# RTnT - Raku Tips ‘n Tricks - https://rakudoweekly.blog/
#
# perhaps more than one TnT can be extracted from this
# demonstration of my favorite Raku -oFun features
#
##############################################
# How many -oFun Raku features can you spot? #
##############################################
#
# Source: https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Raku

#| Recursive, single-thread, random pivot, single-pass, quicksort implementation
multi quicksort(\a where a.elems < 2) { a }
multi quicksort(\a, \pivot = a.pick) {
	my %prt{Order} is default([]) = a.classify: * cmp pivot;
	|samewith(%prt{Less}), |%prt{Same}, |samewith(%prt{More})
}

#| Recursive, parallel, random pivot, single-pass, quicksort implementation
multi quicksort-parallel-naive(List \a where a.elems < 2 --> List) { a }
multi quicksort-parallel-naive(List \a, \pivot = a.pick --> List) {
	my %prt{Order} is default([]) = a.classify: * cmp pivot;
	my Promise $less = start { samewith(%prt{Less}) }
	my $more = samewith(%prt{More});
	await $less andthen |$less.result, |%prt{Same}, |$more;
}

my @algorithms-under-test = &quicksort, &quicksort-parallel-naive;

##############################################
# test algorithms
use Test;
my UInt $batch = 1;
my UInt $degree = max 2, $*KERNEL.cpu-cores - 1;
plan @algorithms-under-test.elems;
given <3 4 a z 🎮 🐧> {
    @algorithms-under-test.pick(*).race(:$batch, :$degree).map: -> &algo {
        is-deeply &algo($_), .sort, "{&algo.name} vs. build-in sort";
    }
}
done-testing;
 
##############################################
# run algorithms on STDIN
gather {
    given $*IN.words -> @unsorted {
        LEAVE {dd @unsorted}
        take hyper for @algorithms-under-test {
            .name, .(@unsorted) 
        }
    }
} andthen .deepmap: *.say
INFO