2017-01-19 34 views
0

我正在尝试实现一个列表,它在Tuple中搜索某个模式(遍历元组列表,然后清空这些元素,然后写入与模式匹配的元素)最后,我输入的列表将是空的,然后将匹配的元组写入此列表中。Haskell错误:函数中的非穷举模式

(使用的函数做所有的工作 - 错就错在这部分)

PatternFinder :: String -> [(String, String)] , [(String, String)] 
PatternFinder = n ((b,a) : xs) = 
if PatternFits n a 
then do 
PatternFinder n xs 
(b,a) : xs 
else PatternFinder n xs 
+1

您无法定义以大写字母开头的函数。这是为数据构造函数保留的。您的缩进也会导致语法错误。将来,请逐字粘贴您的实际编译代码。 –

回答

2

从你的问题的文本看来,你似乎想要一个基于每一对的第二项的简单过滤器。

patternFinder n = filter (patternFits n . snd) 

举例说明这是如何工作的。

filter ((==1) . snd) [('a',1),('b',2),('c',1)] 

回报[('a',1),('c',1)]

在乍得吉尔伯特的答案,但是,没有当时的条款中没有递归:

if patternFits n a 
then (b,a) : xs 
else patternFinder n xs 

这第一场比赛后返回列表的后缀。如果这是预期的行为,你也可以使用:

patternFinder n = dropwhile (not . patternFits n . snd) 

作为这方面的一个例子:

dropWhile (not . (==2) . snd) [('a',1),('b',2),('c',1)] 

回报[('b',2),('c',1)]

而且,在你的问题的文本,你需要将你输入的列表将是空的。请注意,这些函数对原始列表无效,但返回新列表。

+0

哇这很好解释,我其实是想弄清楚这工作现在 - 感谢您的帮助:) – Fapprentice

2

你是不是第二个参数是空单的情况。为了详尽,你必须处理这种模式:

patternFinder n [] 

你还要其他的语法错误。函数名称必须以小写字母开头,签名由->分隔,而不是,,并且您不需要do语句,因为您不在monad上下文中。它应该看起来更像这样:

patternFinder :: String -> [(String, String)] -> [(String, String)] 
patternFinder n [] = [] 
patternFinder n ((b,a) : xs) = 
    if patternFits n a 
    then (b,a) : xs 
    else patternFinder n xs 
+0

我试过了,通过添加“patternFinder n [] = xs”,但是我总是得到变量不在范围内...... – Fapprentice

+0

必须是一个问题,它涉及到我先清空列表然后尝试再次写入,然而我不知道如何解决这个问题...... – Fapprentice

+0

你有很多其他的语法错误 –

相关问题