gpt4 book ai didi

haskell - 模式匹配 Data.Sequence 类似列表

转载 作者:行者123 更新时间:2023-12-04 02:43:25 24 4
gpt4 key购买 nike

我正在使用 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.viewlS.viewr ,但似乎无法弄清楚如何。

最佳答案

从 GHC 7.8 开始,您可以使用 pattern synonyms连同 view patterns以此目的:

{-# 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.|>)

关于haskell - 模式匹配 Data.Sequence 类似列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com