From Listable to Sortable
Once there is a notion of Listable
with its methods acting on its instances like lists,
the notion of Sortable
is a natural extension. Here I extend Listables
to have behaviors such as sort
and shuffle
. The sort
is a quicksort and the shuffle
is a key shuffle.
import System.Random
:l Listable
System.Random
is imported here as a method for producing a stream of random numbers is required for a key shuffle.
The next few lines gives a function which produces such a stream. Notice, I am not yet concerned about a random seed.
randos :: [Integer]
randos = randomRs (0, 10^6) $ mkStdGen 32
take 10 randos
Next, I introduce the class Sortable
. Notice that most ‘special’ methods are supplied by Listable
. The Sortable
methods are gotten ‘for free’. Lastly, instances of Sortable
[a]
and Integers
are given. The one caveat being that Ord a => [a]
.
class (Ord s, Listable s) => Sortable s where
sort, shuffle :: s -> s
sort ns | ns == unit = unit
| otherwise = branch smaller ns +++ headL ns +++ branch larger ns
where
branch f xs = sort.f (headL xs) $ tailL xs
smaller n = filterL (<= n)
larger n = filterL (> n)
shuffle = eval . map snd . sort . zipS randos
where
eval = foldr cons unit
zipS [] s = []
zipS (x:xs) s | s == unit = []
| otherwise = (x, headL s) : zipS xs (tailL s)
instance Sortable Integer where
instance Ord a => Sortable [a] where
sort 23478662345
shuffle 23423423
shuffle [1..10]
sort.shuffle $ [1..10]