I need to write a function checkNode that accepts a graph in form of:
[(1,[2,3]), (2, [3,4])]
as an argument where the first integer in a Tuple is a Node and the list shows all the other Nodes the initial Node is connected to.
checkNode has a second parameter, an Integer.
checkNode [(1,[2,3]), (2, [3,4])] 2
outputs True, because 2 is a node in the graph, whereas
checkNode [(1,[2,3]), (2, [3,4])] 7
outputs False.
Here's what I have so far:
checkNode :: (Eq a, Num a) => [(a, [a])] -> a -> Bool
checkNode [] _ = False
checkNode [(x,_):d] n = if (n == x) then True else checkNode d n
and here's the error:
test2.hs:53:12: error:
• Couldn't match expected type ‘(a, [a])’
with actual type ‘[(a, [a])]’
• In the pattern: (x, _) : d
In the pattern: [(x, _) : d]
In an equation for ‘checkNode’:
checkNode [(x, _) : d] n = if (n == x) then True else checkNode d n
• Relevant bindings include
checkNode :: [(a, [a])] -> a -> Bool (bound at test2.hs:52:1)
| 53 | checkNode [(x,_):d] n = if (n == x) then True else checkNode d n |
^^^^^^^
CodePudding user response:
The solution was to alter the way the function reads the graph input:
checkNode :: (Eq a, Num a) => [(a, [a])] -> a -> Bool
checkNode [] _ = False
checkNode ((x,_):d) n = if (n == x) then True else checkNode d n
namely enclose the graph in the round brackets.
CodePudding user response:
If you want to only check if there is an edge leaving that item (so the query is in the first item of one of the 2-tuples), you can check with:
checkNode :: (Foldable f, Eq a) => f (a, [b]) -> a -> Bool
checkNode graph q = any ((q ==) . fst) graph
this will check if any item in the Foldable
(that can be a list) is a 2-tuple with q
as first item.
This will not check if there is an incoming edge for a node, so 4
is not a node of the graph [(2, [4])]
for example.