分开元素并返回haskell

时间:2018-04-23 15:31:14

标签: haskell

我需要实现一个Haskell函数,该函数以(U "NAME", I "Item Name", INT_HERE)的形式获取元素列表并返回每个元素的“Item Name”部分,但是我想只返回每个不同的“Item name”一次如果重复,我已经实现了仅过滤列表中不同值的函数(dis :: Eq a => [a] -> [a])

例如,对于此输入:

stackOverFlowFunction [(U "John" , I "GTX 1070", 5), 
                       (U "Ahmed" , I "Lenovo Y5070", 3), 
                       (U "Carole" , I "Honda Civic", 5), 
                       (U "Nada" , I "Honda Civic", 4),
                       (U "Ahmed" , I "GTX 1070", 1)]

它应该返回

[I "GTX 1070", I "Lenovo Y5070", I "Honda Civic"]

2 个答案:

答案 0 :(得分:3)

您稍作修改后的nub

data I = I String deriving (Show, Eq)
data U = U String deriving (Show, Eq)

nubI :: [(U, I, Int)] -> [I]
nubI = nub . map (\(_, i, _) -> i)

这给了......

> nubI [(U "John" , I "GTX 1070", 5), (U "Ahmed" , I "Lenovo Y5070", 3), (U "Carole" , I "Honda Civic", 5), (U "Nada" , I "Honda Civic", 4),(U "Ahmed" , I "GTX 1070", 1)]
[I "GTX 1070",I "Lenovo Y5070",I "Honda Civic"]

答案 1 :(得分:2)

您的函数采用列表,但只返回单个值。按原样,您需要递归提取的值添加到其余此类值的列表中。

stackOverflowFunction [] = []
stackOverflowFunction ((b,a,c):xs) = a : stackOverflowFunction xs

但是,这只是复制map函数实现的递归方案:

extract :: (b, a, c) -> a
extract (_, a, _) = a

stackOverflowFunction :: [(b, a, c)] -> [a]
stackOverflowFunction xs = dis (map extract xs)
-- stackOverflowFunction xs = dis (map (\(_,a,_) -> a) xs)

有了这些,

>>> extract (U "John" , I "GTX 1070", 5)
I "GTX 1070"
>>> stackOverflowFunction [(U "John" , I "GTX 1070", 5), (U "Ahmed" , I "Lenovo Y5070", 3), (U "Carole" , I "Honda Civic", 5), (U "Nada" , I "Honda Civic", 4),(U "Ahmed" , I "GTX 1070", 1)]
>>> [I "GTX 1070",I "Lenovo Y5070",I "Honda Civic"]

(推定dis函数的输出。)