I want to make a function that recieves a list of pairs (e.g. [(3,'a'),(7,'d'),(1,'c')]) and a key (e.g. 3) and returns the value for that key (in this example 'a').
The function I've written works fine if the key exists but if i try to return null when i did not find a key that matches - I get an error.
the function is :
lookup1 k lst = lookupH1 k lst
where
lookupH1 k lst
| ((length lst) == 0) = null -- this is the problematic line
| ((fst (head lst)) == k )= snd (head lst)
| otherwise = lookupH1 k (tail (lst))
what can I do to solve this?
It's usually best to first stub out your types and then let the compiler guide you.
In this case, it looks like the signature you are looking at right now is:
lookup1 :: Int -> [(Int,Char)] -> Char
However, Haskell doesn't have a null that can replace the Char as the return type. Therefore, it's common practice to use Maybe instead. The new type signature would then be.
lookup1 :: Int -> [(Int,Char)] -> Maybe Char
This would mean that upon finding the value v, you would yield "Just v" and in the case where you don't, it would yield "Nothing".
I hope I'm not giving away too much, but this is a slightly simpler version of your function using pattern matching.
lookup1 :: Int -> [(Int,Char)] -> Maybe Char
lookup1 k lst = lookupH1 lst
where
lookupH1 [] = Nothing
lookupH1 ((k',v):lst')
| k == k' = Just v
| otherwise = lookupH1 lst'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With