Purescript中的惯用Haskell RLE

Hug*_*ira 4 haskell purescript

所以,我试图通过转换99个Haskell问题中的一些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] 
Run Code Online (Sandbox Code Playgroud)

我很快就了解到:

  • 没有[]速记;
  • 没有(,)元组;
  • 我们需要用显式量化多态函数forall;
  • cons (:)Array类型没有与运算符匹配的模式;
  • ...

所以这就是问题:在Purescript中编写上述解决方案的最惯用方法是什么

Chr*_*ann 5

没有[]速记

在PureScript中,我们显式调用类型构造函数 List

没有(,)元组

在PureScript中,我们要么使用Tuple类型,要么使用其他常见模式来使用具有描述性名称的记录,就像我在下面的解决方案中所做的那样.

我们需要用明确的forall来量化多态函数

没有与Array类型的cons(:)运算符匹配的模式

我们可以在List类型上进行模式匹配:.匹配头部的模式Array几乎不是一个好主意,因为它对性能非常不利.

我已经使用上面提到的几点将您的解决方案转换为PureScript.该示例也可以在以下位置进行尝试和运行:http://try.purescript.org/?gist = f45651a7f4d134d466d575b1c4dfb614&backend = core

-- Problem 10

rle :: forall a. (Eq a) => List a -> List {repetitions :: Int, value :: a}
rle Nil = Nil
rle (x:xs) = case span (_ == x) xs of
  {init: h, rest: t} -> {repetitions: length h + 1, value: x} : rle t

-- Problem 11

data RleItem a = Pair Int a | Single a

encode :: forall a. Eq a => List a -> List (RleItem a)
encode = map unpack <<< rle 
   where 
    unpack = case _ of
      {repetitions: 1, value} -> Single value
      {repetitions, value} -> Pair repetitions value

-- Problem 12

decode :: forall a. List (RleItem a) -> List a
decode = concatMap unroll
  where unroll (Pair y x) = replicate y x
        unroll (Single x) = singleton x 
Run Code Online (Sandbox Code Playgroud)