Joao Parente
Joao Parente

Reputation: 453

How to do lists of pairs?

So im suposed to do a function that receives a list of pairs and gives the firsts elements of the pair , the problem is that i only know how to write a list of pair if it is only 1 pair

primeiros :: [(a,b)] -> [a] 
primeiros (a,b) = undefined

but the problem is that i dont know how to write if is more than 1 pair , i tried this :

primeiros [(a,b),(as,bs)] = undefined

but this obvious wont work because it will only do something if the list has 2 pairs , i want something that works for whatever pairs.

Upvotes: 0

Views: 117

Answers (2)

user1781434
user1781434

Reputation:

You create a list with the first element like so:

primeiros :: [(a,b)] -> [a]
primeiros (x:xs) = [fst x] ++ primeiros xs

fst returns the first element of a pair, and you can also use map:

primeiros :: [(a,b)] -> [a]
primerios = map fst

Upvotes: 2

Mark Seemann
Mark Seemann

Reputation: 233495

Pairs

You can create a pair like this:

Prelude> (42, "Foo")
(42,"Foo")

This is a pair where the first element is a number, and the second element is a String.

That pair is a both a pair of values, but you can also think of it as a single value.

List

One way to write a list of values is like this:

Prelude> [1,5,2,7,1337]
[1,5,2,7,1337]

This is a list of five numbers.

Another way to write the same list is like this:

Prelude> 1:5:2:7:1337:[]
[1,5,2,7,1337]

Now that you know how to write a pair as a single element, and how to write a list of elements, I'm sure you can figure out how to write a list of pairs.

Upvotes: 0

Related Questions