Haskell 使用模式识别将列表拆分为子列表

Haskell Split list into Sublist using pattern recognition

如果出现特定模式,我正在尝试拆分包含 I 和 Os 的数组。

假设我有一个输入,看起来像这样:

data Bit = O | I  deriving (Eq, Show)    
let b = [I,I,O,O,O,O,O,I,I,O,O,O,I,O]

这就是我生成的内容,当编码 [[Bool]] -> [Bit] 时,我的编码函数的相应输入将是 let a = [[True, False, False, True],[False, False],[False]]

现在我的 objective 是解码我生成的内容,所以我需要一个函数让我从 b 到 a。

但我无法想出一种方法将 b 列表拆分为 3 个子列表,每次它读取 I、O 或 I、I。每个奇数字母代表后续成员或起始数组成员。我基本上是复制utf unicode编码。

所以我正在尝试构建一个可以让我从 b 到 a 的函数。 一段时间后我想到了这个:

split :: [Bit] -> [[Bit]]
split (x1:x2:xs) = if (x1 == I)
                    then [x2 : split xs]
                    else x2 : split xs

而且我不知道如何将列表拆分为子列表。非常感谢任何一种advice/help/code

编辑:

split :: [Bit] ->[[Bit]]
split [] = []
split xs = case foo xs of (ys,I,x2) -> -- generate new subarray like [...,[x2]]
                    (ys,O,x2) -> -- append existing subarray with value x2 [.....,[previous values]++x2]

foo :: [a] -> ([a],x1,x2)
foo x1:x2:input =  (input,x1,x2)

那 2 条评论是我最后需要弄清楚的事情。在那之后我完成了:)

如果将 b 馈入函数 split,我想要这个输出:[[I,O,O,I],[O,O],[O]] 最后一步是从 b 到 [[True, False, False, True],[False, False],[False]]

我会从 if (x1 == 1) ...

开始

如果 x1 是一个可以是 IOBit,为什么要将它的相等性与 Num1?

如果我做对了,你需要这样的东西:

split [] = []
split xs = case foo xs of (ys,r) -> r : split ys

foo :: [a] -> ([a],r)
foo = undefined

foo 中,列表应该被部分消耗,并且 returns 列表的其余部分和要收集的值。

编辑:

data Bit = O | I deriving (Eq, Show)    

sampleA = [[True, False, False, True],[False, False],[False]]
sampleB = [I,I,O,O,O,O,O,I,I,O,O,O,I,O]

type TwoBit = (Bit,Bit)

twobit (x:y:xs) = (x,y) : twobit xs
twobit _ = []

split :: [TwoBit] -> [[Bool]]
split [] = []
split xs = case spli xs of (ys,r) -> r : split ys
    where
        spli :: [TwoBit] -> ([TwoBit],[Bool])
        spli (x:xs) = case span (not . pterm) xs of 
            (ys,zs) -> (zs, map ptrue $ x:ys)

        pterm x = (I,O) == x || (I,I) == x
        ptrue x = (O,I) == x || (I,I) == x

splitTB = split . twobit

main = print $ splitTB sampleB == sampleA

PS 看起来像 s -> (s,a) 的函数也可以表示为状态 monad。