简体   繁体   English

haskell元组列表,具有唯一的元组

[英]haskell list of tuples, with unique tuples

I come from a Python and Java background so Haskell is quite different for me. 我来自Python和Java背景,因此Haskell对我来说是完全不同的。 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. 我有一个有序的元组列表,[(name,studentNumber)],我想过滤该列表,以便每个学生和每个StudentNumber仅出现一次。 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. 由于元组是有序的,因此我想保留名称或studentNumber的第一个实例,并删除可能出现的其他任何实例。

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. 我尝试做一个列表列表,但是不确定如何检查名称或号码是否已添加到列表中。

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. 第一次调用nubBy将产生一个列表,其中每个名称仅出现一次,然后将其传递给第二个列表,从而产生一个列表,其中每个数字仅出现一次。

Just using nub will result in a list in which each (name,number) pair occurs only once; 仅使用nub会得到一个列表,其中每个(name,number)对仅出现一次; 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.) (当然,使用累加器的自定义设置会更快。)

You can spy on Data.List sources and write your extended nub function: 您可以监视Data.List 并编写扩展的nub函数:

type Student = (Name, Number)
type Name = String
type Number = Int

unique :: [Student] -> [Student]
unique = go [] [] 
  where
    go unames unumbers (s@(name, number):ss)
      | name `elem` unames || number `elem` unumbers = go unames unumbers ss
      | otherwise = s : go (name:unames) (number:unumbers) ss
    go _ _ [] = []

Should do what you want. 应该做你想做的。

为了使列表唯一化,序言中总是包含nub函数,我认为这应该完全满足您的需求!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM