You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Haskell实现提取元组列表中去重的Item Name函数?

Solution for Extracting Unique Item Names in Haskell

Got it, let's break this down into simple, actionable steps. First, let's confirm the data types you're working with—since you mentioned U and I constructors, I assume they're defined like this (adjust the pattern matching if your actual definitions differ):

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

Your input list will have the type [(User, Item, Int)], which matches your sample input structure perfectly.

Step 1: Extract the "Item Name" from each tuple

We need to pull out the string inside the I constructor from every triple. Use map with a lambda that pattern-matches on the tuple—we don't care about the U value or the integer, so we can ignore those with underscores:

extractItemNames :: [(User, Item, Int)] -> [String]
extractItemNames = map (\(_, I itemName, _) -> itemName)

This takes your input list and returns a list of all item names (including duplicates). For your sample input, this would give something like ["GTX 1070", "Lenovo Y5070", ...].

Step 2: Deduplicate using your dis function

You already have a deduplication function dis :: Eq a => [a] -> [a], so we just compose it with our extraction function using Haskell's function composition operator (.). This gives us a single clean function that handles both steps:

extractUniqueItems :: [(User, Item, Int)] -> [String]
extractUniqueItems = dis . extractItemNames

If you prefer to skip the separate extraction function, you can write it inline:

extractUniqueItems = dis . map (\(_, I itemName, _) -> itemName)

Full Example

Let's test this with a concrete sample that includes a duplicate item:

sampleInput = [(U "John" , I "GTX 1070", 5), (U "Ahmed" , I "Lenovo Y5070", 3), (U "Sarah", I "GTX 1070", 4)]

-- Running extractUniqueItems sampleInput will output:
-- ["GTX 1070", "Lenovo Y5070"]

The order of the unique items depends on how your dis function handles ordering—if it behaves like Data.List.nub, it'll keep the first occurrence of each item and discard later duplicates.

内容的提问来源于stack exchange,提问作者Omar Hussein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:07:36