So, I'm trying to learn Purescript by converting some Haskell code I had from the 99 Haskell Problems, and quickly got into a situation where I know how to solve it, but it is simply too ugly™. Here's the Haskell code for problems 10, 11 and 12; basically some RLE encode and decode 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 learned that:
- There's no
[]
shorthand; - There's no
(,)
tuples; - We need to quantify polymorphic functions with an explicit
forall
; - No pattern matching with
cons (:)
operator for theArray
type; - ...
So here's the question: what is the most idiomatic way to write the above solution in Purescript?