0
votes

i was trying to made a function to verify if a Node exists in a list (i'm working with graphs):

buscaNodo :: [(Nodo,Peso)]->Nodo->Bool
buscaNodo _[] = False
buscaNodo ((a,b):ar) n 
        |(n == a)= True || (buscaNodo ar n)
        |(n /= a)= False || (buscaNodo ar n)
        |otherwise = False 

That function returns me a true always that the node exists in the list; but if it doesn't exists in the list haskell show me an error : Non-exhaustive patterns in function buscaNodo, i need some help please, i was learning haskell recently and dont have the neccesary knowledge for solve that problems by myself. I'm so sorry for my dreadful english. Thank you for all

2
Can you provide the definitions of Nodo, Peso, and the error message you get? These bits of information make it much easier to figure out what the actual problem you have is. - bheklilr
Also, I would suggest using higher level functions to solve this problem. If all you need to do is find if n is in that list, then you can do so quite easily with a combination of map fst and elem, such as buscaNodo graph n = elem n $ map fst graph. This doesn't solve the error you're getting, but it would be an alternate solution to what you're trying to do. - bheklilr
'Nodo' is only a 'String' . 'Peso' is a duple of '(Int,Float)'. In this function i dont use 'Peso', i only want to know if a String exists in a list. But when it doesnt exists, appears the error: 'Non-exhaustive patterns in function buscaNodo' - Ray Montiel
Looks like the argument order is wrong in one of the first equation. - n. 1.8e9-where's-my-share m.

2 Answers

5
votes

The problem is exactly because of the definition for type Nodo = String. Since String itself is a list of Chars, this means that when you have the pattern

buscaNodo _ [] = False

This is equivalent to

buscaNodo _ "" = False

You're actually matching on the empty string. What you probably meant was to have these arguments switched:

buscaNodo [] _ = False

Where looking up any element (_) on an empty list will always return False.

You can also greatly simplify this definition by using built-in functions that come with Haskell:

buscaNodo :: [(Nodo, Peso)] -> Nodo -> Bool
buscaNodo graph node = elem node $ map fst graph

And now you don't have to worry about any cases at all.

4
votes

You have two cases for your buscaNodo function. One is when the second argument is the empty string. The other is when the first argument is a non-empty list.

But what about the case when both the first argument is an empty list and the second is a non-empty string? When the function is called with the first argument empty and the second argument non-empty, neither of the two definitions fits. Thus you get a non-exhaustive pattern error.