[英]Removing a tuple that contains a null from list in haskell
美好的一天!
所以我試圖寫一個函數是Haskell如下
remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ] -> [ ([String], Int) ]
remove_nulls listofpair (y:ys)
| null listofpair = (y:ys)
| null (fst(head listofpair))= remove_nulls (tail listofpair) (y:ys)
| otherwise = remove_nulls (tail listofpair) (y:(head listofpair):ys)
哪個輸入看起來像這樣
remove_nulls [ ([],0) , (["abc", "dce"], 2) ] []
想法是,如果元組的第一個值中包含null,則它將從列表中刪除該元組。 但是,每次調用它時,它都會返回“ remove_nulls函數中的非窮盡模式”。
我嘗試更改基本情況,但始終得到相同的結果。 任何幫助和利用都是很好的(目前只是學習Haskell)。
如果您只想刪除所有具有空第一字段的對,
removeNulls xs = filter (not . null . fst) xs
會做到這一點。 如果您還不熟悉(not . null . fst)
的表示法,則這只是編寫函數\\pair -> not (null (fst pair))
一種較短方法。 有關更多說明,請參見此SO問題 。
您的原始函數似乎嘗試在第二個輸入列表的第一個元素之后插入第一個列表中的好元素,但由於它沒有涵蓋第二個列表為空的情況而無法工作。
remove_nulls
應該獲取列表並因此返回一個新列表:
remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ]
remove_nulls lst = [(x,y) | (x,y) <- lst, (not.null) x]
因為您調用帶有空列表作為第二個參數的remove_nulls,並且僅提供了第二個參數至少具有一個元素的定義(這是第一行的(y:ys)
模式),所以找不到匹配項,導致您看到錯誤消息。
我認為(但沒有嘗試過)如果您擺脫y:
比賽,它應該編譯(但也許還沒有做您想要的!)。 因此,嘗試這樣的事情:
remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ] -> [ ([String], Int) ]
remove_nulls listofpair ys
| null listofpair = ys
| null (fst (head listofpair))= remove_nulls (tail listofpair) ys
| otherwise = remove_nulls (tail listofpair) (head listofpair:ys)
您錯過添加一個額外的條件:當第二個列表為空時
remove_nulls :: [([a], t)] -> [([a], t)] -> [([a], t)]
remove_nulls [] ys = ys
remove_nulls (([], _):xs) ys = remove_nulls xs ys
remove_nulls (x:xs) [] = remove_nulls xs [x] -- new condition
remove_nulls (x:xs) (y:ys) = remove_nulls xs (y:x:ys)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.