10

我正在使用Data.Sequence列表来获得更好的性能。使用列表,我们可以执行以下操作

foo :: [Int] -> Int
foo [] m = m
foo (x:xs) m = ...

怎么能做到这一点Data.Sequence。我尝试了以下方法:

foo:: S.Seq Int -> Int
foo S.empty m = m
foo (x S.<: xs) m = ...

我认为解决方案涉及使用S.viewland S.viewr,但似乎无法弄清楚如何。

4

2 回答 2

15

从 GHC 7.8 开始,您可以将模式同义词视图模式一起用于此目的:

{-# LANGUAGE ViewPatterns, PatternSynonyms #-}

import qualified Data.Sequence as Seq

pattern Empty   <- (Seq.viewl -> Seq.EmptyL)
pattern x :< xs <- (Seq.viewl -> x Seq.:< xs)
pattern xs :> x <- (Seq.viewr -> xs Seq.:> x)

从 GHC 7.10 开始,您还可以将其变成双向模式的同义词,这样Empty,(:<)(:>)也可以用作“构造函数”:

{-# LANGUAGE ViewPatterns, PatternSynonyms #-}

import qualified Data.Sequence as Seq

pattern Empty   <- (Seq.viewl -> Seq.EmptyL)  where Empty = Seq.empty
pattern x :< xs <- (Seq.viewl -> x Seq.:< xs) where (:<)  = (Seq.<|) 
pattern xs :> x <- (Seq.viewr -> xs Seq.:> x) where (:>)  = (Seq.|>) 
于 2015-06-29T02:28:29.663 回答
13

ViewPatterns可能是去这里的方式。您的代码不起作用,因为您需要先调用orviewl来获取类型or的东西。可以很好地处理:viewrSeqViewLViewRViewPatterns

{-# LANGUAGE ViewPatterns #-}

foo (S.viewl -> S.EmptyL)    = ... -- empty on left
foo (S.viewl -> (x S.:< xs)) = ... -- not empty on left

这相当于:

foo seq = case S.viewl seq of
    S.EmptyL    -> ...
    (x S.:< xs) -> ...
于 2015-06-29T01:48:02.443 回答