2017-03-08 7 views
4

私は99 Haskell ProblemsのHaskellコードを変換してPurescriptを学習しようとしていますが、すぐに解決方法を知っている状況になっていますが、単純にtoo ugly™。ここで問題10,11,12のハスケルコードです。基本的には、いくつかのRLEエンコードとデコード機能:私はすぐに学んだことをPurescriptのIdiomatic 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で上記溶液を書くための最も慣用的な方法は何ですか?

答えて

5

なし[]速記

はありませんPureScriptでは、型コンストラクタを明示的に呼び出します。List

タプルはありません

PureScriptでは、私はTupleタイプを使用していますが、別の一般的なパターンは、下のソリューションで行ったように、わかりやすい名前のレコードを使用することです。我々は

はい

FORALL明示して多型の機能を定量化する短所と一致するパターン(:)アレイタイプのオペレータ

我々は缶を必要としない

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 
1

これは、(1ない完全いえ:1)これまでのところ、私自身の答えだった私はそれを受け入れることを期待していないものの、:

data RleItem α = Pair Int α | Single α 

encode :: forall α. (Eq α) => List α -> List (RleItem α) 
encode Nil = Nil 
encode [email protected](x:_) = let s = span ((==) x) p in 
    pack (length s.init) : encode s.rest where 
    pack 0 = Single x 
    pack y = Pair y x 

decode :: forall α. List (RleItem α) -> List α 
decode = (=<<) unpack where 
    unpack (Single x) = pure x 
    unpack (Pair y x) = replicate y x 
関連する問題