Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extracting the first element of a tuple via list comprehension in haskell

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading