简体   繁体   中英

Haskell - Searching list of Tuples, returning second elements

So I know many variations of this question have been asked but I've been reading posts for hours and I'm just stuck. I'm getting better at haskell but not fully comprehending everything.

For starters, this is an assignment so while I don't want the answer looking for some guidance.

We have these 4 types declared for this assignment:

type Node = Integer
type Edge = (Integer, Integer)
type Graph = [Edge]
type Path = [Node]

What I am currently working is a function which takes a Node and a Graph and returns a list of Nodes that are connected to the Node passed in.

I'm really struggling with how to recursively return the second element in the tuple once I've found the source node i'm looking for. I know I need to be using fst to grab the first element of each tuple for comparison but then I get lost here, I'm stuck on how to correctly return the second element (add it to my list) and then proceed through the remaining list of tuples.

Neighbors :: Node -> Graph -> [Node]
Neighbors nd gr = 

I've been reading about filter but I'm not sure that would work in this scenario as that returns pairs if I understand correctly. Looking for any guidance, thank you

You can indeed use filter to find edges that leaves from a given node. Then you need to take second element of each of this edge. You need map for that. So you write:

neighbors nd gr = map snd $ filter (\x -> fst x == nd) gr 

(Note that Haskell would not allow you to start name of the function with capital letter). If you want to be cool you can write it in almost point-free way:

neighbors nd  = map snd . filter ((==nd) . fst ) 

And if you want to make it easier to read you can use list comprehensions:

neighbors nd gr = [ y | (x,y) <- gr, x==nd ]

filter could indeed be used to return only those edges in the graph that are of interest to you (ie, those leading out from the target node). Then you'd have a list of edges, when what you really want is a list of nodes. Can you think of a function that can transform a list of edges into a list of nodes, after you've filtered down to only the edges you want?

edges :: [Edge]
f :: Edge -> Bool
filter f edges :: [Edge]
g :: [Edge] -> [Node]
g (filter f edges) :: [Node]

Above is a reasonable set of steps you could take, if you can think of appropriate f and g functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM