簡體   English   中英

Haskell錯誤:功能中的非窮盡模式

[英]Haskell error: Non-exhausive patterns in function

我正在嘗試實現一個列表,該列表在元組中搜索某個模式(遍歷元組列表,將其清空,然后將其寫入與模式匹配的字符串),最后我輸入的列表將為空,然后它將匹配的元組寫入此列表。

(所使用的功能可以完成所有工作-這部分是錯誤的)

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

您不是第二個參數為空列表的情況。 為了詳盡無遺,您必須處理以下模式:

patternFinder n []

您還遇到其他語法錯誤。 函數名稱必須以小寫字母開頭,簽名用->而不是,分隔,並且您不需要do語句,因為您不在單子上下文中。 它可能看起來應該像這樣:

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

從問題的文本來看,您似乎想要一個基於每對第二個術語的簡單過濾器。

patternFinder n = filter (patternFits n . snd)

作為其工作原理的說明。

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

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

但是,在乍得·吉爾伯茨(Chad Gilberts)的答案中,then子句沒有遞歸:

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)]

同樣,在問題文本中,您要求輸入的列表為空。 請注意,這些函數對原始列表不執行任何操作,而是返回新列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM