Reputation: 75
I have written several functions that operate on a list storing keys and values in the same list, e.g.
myList = [k1, v1, k2, v2]
but instead of operating on a list, I need to make my own data structure called Translator for my functions to operate on.
Here is one of the functions, it simply checks if a key is in the list. (I am a beginner to Haskell and am not allowed to use any functions I haven't written myself so I know there is probably a lot of room for improvement with this function but that's not what I'm looking for)
hasTranslation _ [] = False
hasTranslation k l = hasTranslation' k l 0
hasTranslation' k l@(x:xs) n
| n `mod` 2 == 1 && xs == [] = False
| n `mod` 2 == 1 = hasTranslation' k xs (n+1)
| k == x = True
| otherwise = hasTranslation' k xs (n+1)
I need to make a data structure that stores keys and values of the same type in a list type format and then amend my functions to do this.
I have tried several combinations of type Translator a = [a]
and data Translator = IntTranslator [Int] deriving (Show, Eq)
though have not been able to wrap my head around how to apply these to how I need them to work.
I should note that my data structure NEEDS to work for keys/values of type Int and String and anything else is a bonus.
Any help greatly appreciated
Upvotes: 1
Views: 143
Reputation: 3818
Update: it has to be stored in one single list, wrap key and value into one might be an option
data KV k v = K k | V v deriving Show -- or use Either
type KVList k v = [KV k v]
hasTranslation :: (Eq k) => k -> KVList k v -> Bool
hasTranslation _ [] = False
hasTranslation k ((V _) : xs) = hasTranslation k xs
hasTranslation k ((K k') : xs)
| k == k' = True
| otherwise = hasTranslation k xs
Old: A direct translation might be [(k, v)]
.
type KVList k v = [(k, v)]
hasTranslation :: (Eq k) => k -> KVList k v -> Bool
hasTranslation _ [] = False
hasTranslation k ((k', _) : xs)
| k == k' = True
| otherwise = hasTranslation k xs
Upvotes: 1