0

I have such a data type :

data Node a = Node
    { label :: a,
        adjacent :: [(a,Int)] } deriving Show

Example : ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) I want to get the label from this structure, I wrote this function (and several other combinations which I thought might work) :

giveLabel Node a [(c,b)] = a; 

But I keep getting errors. Can you tell me how should I change my function? Thanks

1 Answer 1

7
giveLabel (Node a [(c,b)]) = a

Is the syntax you want - defining functions uses the same rules of precedence as calling them, and according to those rules, you defined a function giveLabel with three arguments (Node, a, and [c,b]); and that was illegal because in that context Node was missing arguments.

Even that probably isn't what you want - the pattern [(c,b)] only matches lists with exactly one item in. Since you don't care about the list of neighbours you can write:

giveLabel (Node a xs) = a

...where xs will bind to the whole list of neighbours; but actually since you don't even care about that, you can write:

giveLabel (Node a _) = a

...where _ is a useful way of pattern matching against a parameter you aren't going to use.

Sign up to request clarification or add additional context in comments.

2 Comments

Main> giveLabel ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) Program error: pattern match failure: giveLabel (Node 'a' [('b',3),('c',2)])
Right. The example I gave you does force the list to be only one item long. Will edit my answer to explain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.