Reputation: 37
I have a created a data similarly like this
data Set = Set Integer [Char]
set1 :: [Set]
set1 = [ Set 1 ['a','f','k']
,Set 2 ['p','q','s']
]
If a given char is in the set1 function and it returns element in set1 or Nothing
checkChar :: Char -> [Set] -> Maybe Set
if i given 'p' to checkChar function with set1 as another parameter,then it should return Set 2 ['p','q','s']
what i tried
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
I got following errors for Line 1 and 2
Couldn't match expected type ‘[Set]’ with actual type ‘Set’
How to solve this?
How to match data that consists multiple arguments but want to check with one of the its argument with other data?
Upvotes: 1
Views: 126
Reputation: 476729
You can not write (… : Set ys zs)
. The (:)
data constructor expects as second item a list of Set
s not a Set
object.
You can match this with:
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
Here we use xs
as tail, which is a (possibly) empty list of Set
s. Furthermore by using as pattern Set y z
, this would only match lists with exactly one item. By using z
, z
will be assigned the entire list of items of the Set
object.
Upvotes: 2