【发布时间】:2017-03-08 23:56:45
【问题描述】:
所以,我正在尝试通过转换我从 99 Haskell Problems 获得的一些 Haskell 代码来学习 Purescript,并很快陷入了我知道如何解决它的情况,但它只是 太丑了™。这是问题 10、11 和 12 的 Haskell 代码;基本上是一些 RLE 编码和解码功能:
-- 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]
我很快就知道了:
- 没有
[]速记; - 没有
(,)元组; - 我们需要用明确的
forall量化多态函数; - 没有与
cons (:)运算符的模式匹配Array类型; - ...
那么问题来了:在 Purescript 中编写上述解决方案最惯用的方法是什么?
【问题讨论】:
标签: haskell purescript