So I'm trying to learn Purescript by converting some Haskell code that I had from 99 Haskell Problems , and quickly got into a situation where I know how to solve it, but it's just too ugly. Here's the Haskell code for tasks 10, 11, and 12; basically some RLE encoding and decoding functions:
-- Problem 10
rle :: Eq α => [α] -> [(Int, α)]
rle [] = []
rle (x:xs) = let (h, t) = span (== x) xs
in (length h + 1, x) : rle t
-- Problem 11
data RleItem α = Pair Int α | Single α deriving (Show)
encode :: Eq α => [α] -> [RleItem α]
encode = map unpack . rle
where unpack (1, x) = Single x
unpack (y, x) = Pair y x
-- Problem 12
decode :: [RleItem α] -> [α]
decode = concatMap unroll
where unroll (Pair y x) = replicate y x
unroll (Single x) = [x]
I quickly realized that:
- No reduction
[]; - No tuples
(,); - We need to quantify explicit polymorphic functions
forall; - Match patterns with the operator
cons (:)for the type Array; - ...
So here is the question: what is the most idiomatic way to write the above solution in Purescript?