Reputation: 980
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?
Upvotes: 3
Views: 20626
Reputation: 1707
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'
Upvotes: 8
Reputation: 72044
Look at the Prelude lookup
function: it returns the type Maybe b
. Specifically, it returns Just x
if x
is the value associated with the key, and Nothing
if the key isn't found.
Upvotes: 2
Reputation: 370357
null
is a function that takes a list and tells you whether or not the list is empty. Since your result is not supposed to be a function, using null
as your result is a type error.
There is no such thing as a null pointer or null reference in Haskell. If a function has, say, the result type Char
and the function terminates successfully (i.e. it does not loop forever or throw an exception), the result of calling that function will always be a Char
value and there is no magical null
entity that's somehow a value of every type.
So you have two options: Either you throw an exception when the key is not found or (and this is the better option) you change the result type of your function to Maybe v
rather than v
.
The type Maybe t
in Haskell has two possible values: Just x
where x
is of type t
or Nothing
. So for your (Int, Char) list, your lookup function can return Just v
when it finds a value for the given key or Nothing
when it does not, and the user of your function can then pattern match on the result to find out whether a value was found or not and to get at the value if it was found.
Upvotes: 2