Sprout
Sprout

Reputation: 650

Extracting a single value from a tuple in a list in Haskell

So I have a list of tuples

lis = [(5,6), (5,3), (5,2)]

How would I extract the first value of the tuple i.e 5.

I know that you do head lis to get the head but this returns (5,6), I would just like the 5.

The bigger picture is to be able to obtain the head of a list of tuples and compare it to every value in another list of tuples to see if it matches.

Upvotes: 0

Views: 1059

Answers (2)

MicroParsec
MicroParsec

Reputation: 229

If you would like to use a lamba in another expression:

 (\(x, _) -> x) (head lis)

Or this if you want a function on its own:

 first :: (a, b) -> a
 first (x, _) = x

There is a function that does the same called fst, though.

Upvotes: 1

Sibi
Sibi

Reputation: 48654

That's simple, just use the fst function for extracting the first value from the tuple:

λ> let lis = [(5,6), (5,3), (5,2)]
λ> fst $ head lis
5

Upvotes: 2

Related Questions