Home > Enterprise >  How to match one argument in a data that has multiple arguments with other data?
How to match one argument in a data that has multiple arguments with other data?

Time:10-16

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 typeSet

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?

CodePudding user response:

You can not write (… : Set ys zs). The (:) data constructor expects as second item a list of Sets 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 Sets. 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.

  • Related