haskell list of tuples, with unique tuples

I come from a Python and Java background so Haskell is quite different for me. I'm trying little activities to learn but I am stuck on this .

I have an ordered list of tuples, [(name, studentNumber)], and I want to filter this list so that each student and each studentNumber appears only once. Since the tuples are ordered, I want to keep the first instance of a name or studentNumber and remove any others that may show up.

I tried doing a list comphrenshion, but I'm not sure how to check if a name or number has already been added to the list.

Answers


It sounds as if you'd want (as a first, inefficient approximation) something like this:

import Data.List (nubBy)
import Data.Function (on)

filt = nubBy ((==) `on` snd) . nubBy ((==) `on` fst)

The first call to nubBy will result in a list in which each name appears only once, and that will then be passed to the second, resulting in a list in which each number appears only once.

Just using nub will result in a list in which each (name,number) pair occurs only once; there might still be repetitions of names with different numbers and numbers with different names.

(Of course something custom with an accumulator would be faster.)


Need Your Help

numpy arange values are changing signs unexpectedly

python python-3.x numpy

I am teaching mysef a little about numpy and I have dusted off some of my old undergraduate texts to use for examples. So, I wrote a function without numpy to calculate the deflection in a cantile...

Controlling UITextView's auto scroll speed

ios uitextview uislider autoscroll

i am trying to make an app to view txt files in uitextview. So far i got no problems about fetching the data and stuff.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.