Home > Back-end >  extracting the first element of a tuple via list comprehension in haskell
extracting the first element of a tuple via list comprehension in haskell

Time:05-23

I tried to extract the first element of a tuple in a list of tuples in haskell via list comprehension but somehow it just outputs the first one and then stops, so I decided to do it via recursion which looked like this:

tuples :: (Ord a, Ord b) => [(a, b)] -> [a]
tuples [] = []
tuples ((x,y):xs) = x : tuples xs

now, while this works I would like to know how to do the same thing via list comprehension.

thanks in advance!

CodePudding user response:

Yes, you can use pattern matching in the list comprehension, with:

tuples :: [(a, b)] -> [a]
tuples xs = [ x | (x, _) <- xs ]

But likely the simplest way is just to work with fst :: (a, b) -> a:

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

The typeconstraints for (Ord a, Ord b) are not necessary: nowhere do we use a function defined for types that are members of the Ord typeclass.

  • Related