我創建了一個類似這樣的資料
data Set = Set Integer [Char]
set1 :: [Set]
set1 = [ Set 1 ['a','f','k']
,Set 2 ['p','q','s']
]
如果給定的字符在 set1 函式中并且它回傳 set1 中的元素或 Nothing
checkChar :: Char -> [Set] -> Maybe Set
如果我使用set1作為另一個引數給 checkChar 函式提供了'p',那么它應該回傳Set 2 ['p','q','s']
我試過的
checkChar x [] = Nothing
checkChar x (Set y [z] : Set ys [zs]) --Line 1
| x `elem` [z] = Just $ Set y [z]
| otherwise = checkChar x (Set ys [zs]) --Line 2
第 1 行和第 2 行出現以下錯誤
Couldn't match expected type ‘[Set]’ with actual type ‘Set’
如何解決這個問題?
如何匹配包含多個引數但想要檢查其引數之一與其他資料的資料?
uj5u.com熱心網友回復:
你不能寫(… : Set ys zs)。該(:)資料建構式需要作為第二項的串列中Set不是一個Set物件。
您可以將其與:
checkChar :: Char -> [Set] -> Maybe Set
checkChar x [] = Nothing
checkChar x (Set y z : xs)
| x `elem` z = Just (Set y z)
| otherwise = checkChar x xs
這里我們使用xsas tail,它是一個(可能)空的Sets串列。此外,通過使用 as 模式Set y z,這只會匹配具有恰好一項的串列。通過使用z,z將分配物件的整個專案串列Set。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316801.html
標籤:哈斯克尔
