简体   繁体   English

Haskell列表中的Zip元素

[英]Zip Element in a list in Haskell

I have a problem with the following function in Haskell that zip only elements "B" in a list: 我在Haskell中的以下功能存在问题,该功能仅压缩列表中的元素“ B”:

data El = A | B deriving (Show)

zS :: [El] -> [El]
zS [] = []
zS (A:xs) = A : zS xs
zS (B:xs) = B : zS xs
zS (B:B:xs) = B : zS xs
zS (B:A:xs) = B : A : zS xs

When I test the function zS the result should be: 当我测试功能zS ,结果应为:

zS [B, B, A, A, B, B, B, A, B ] --> [B, A, A, B, A, B ]

but it does not work. 但它不起作用。 Also, when I compile the code, Haskell return a Warning like this: 另外,当我编译代码时,Haskell返回如下警告:

 Warning:
    Pattern match(es) are overlapped
    In an equation for 'zS':

How can I fix this? 我怎样才能解决这个问题?

TL;DR TL; DR

When you define a function with multiple patterns, the patterns which are too specific should be defined at the beginning and the broader patterns should be defined at the end. 当您定义具有多个模式的函数时,应在开头定义过于具体的模式,而在末尾定义更广泛的模式。

Explanation 说明

In your case, 就你而言

zS (B:xs) = B : zS xs

already matches any list which starts with B . 已经匹配任何以B开头的列表。 So, 所以,

zS (B:B:xs) = B : zS xs
zS (B:A:xs) = B : A : zS xs

will already be matched by zS (B:xs) = B : zS xs itself. 将已经由zS (B:xs) = B : zS xs匹配zS (B:xs) = B : zS xs本身。 That is why Haskell is calling it out by saying 这就是为什么Haskell这么说的原因

Pattern match(es) are overlapped

To fix this, define the specific patterns at the beginning, like this 要解决此问题,请在开始时定义特定的模式,如下所示

zS :: [El] -> [El]
zS [] = []
zS (B:B:xs) = B : zS xs
zS (B:A:xs) = B : A : zS xs
zS (A:xs) = A : zS xs
zS (B:xs) = B : zS xs

Note: Your code has a bug, 注意:您的代码有错误,

zS (B:B:xs) = B : zS xs

Here, you are including B , if you find two matches and no matter how many times B is repeated. 在这里,如果找到两个匹配项,并且无论B重复多少次,都包括B Instead, you can recurse like this 相反,您可以像这样递归

zS (B:B:xs) = zS (B:xs)

so that 以便

zS (B:A:xs) = B : A : zS xs

will take care of repeating B s for you. 将为您重复B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM