简体   繁体   English

haskell编程中的数据类型

[英]data types in haskell programming

It is a haskell code to find the first duplicate element in the list. 它是一个haskell代码,用于查找列表中的第一个重复元素。 if you have 2 lists like this:L1 = {1,2,3,4} L2 = {1,2,3,1}then result for 1st would be No duplicate found and result for second should be integer 1.if one list has L3={1,2,1,3,3} answer should still be 1. 如果你有两个这样的列表:L1 = {1,2,3,4} L2 = {1,2,3,1}那么第一个的结果将是没有找到重复,第二个的结果应该是整数1.如果列表有L3 = {1,2,1,3,3}答案应该仍然是1。

I tried doing it but stuck with the condition checking: We will use union datatype. 我试过这样做,但坚持条件检查:我们将使用union数据类型。

data Res a = DuplicateFound a | NoDuplicateFound 
              deriving (Show,Eq)

findDuplicate [] = NoDuplicateFound
findDuplicate (x:xs) = if (condition???)
      where 
      aux x [] = NoDuplicateFound
      aux x (y:ys) = if x == y then DuplicateFound x
                               else aux x ys
                     else NoDuplicateFound

I know its a pathetic code..please help me to improve it. 我知道这是一个可怜的代码..请帮助我改进它。

The key is, as so often, recursion. 关键是,通常是递归。

A list contains a duplicate if either: 列表包含重复项,如果:

  1. the first element has a duplicate in the rest of the list, or 第一个元素在列表的其余部分有一个副本,或者
  2. the rest of the list contains a duplicate 列表的其余部分包含重复项

Add to this that an empty list contains no duplicates, and there's your program. 除此之外,空列表不包含重复项,而且还有您的程序。

(I'd make hasElement just return a Bool, and use Maybe a for the return value.) (我让hasElement只返回一个Bool,并使用Maybe a作为返回值。)

This code is a good start. 这段代码是一个好的开始。 The aux function you have already written searches to see if an element is in a list. 您已编写的aux函数会搜索元素是否在列表中。 Now you just need to check the first element against the rest of the list, and if that fails, then the second element against all elements after it, etc. 现在你只需要检查第一个元素与列表的其余部分,如果失败,那么第二个元素将针对其后的所有元素,等等。

I'll just rename aux to hasElement (never underestimate the clarifying power of a good name): 我只是将aux重命名为hasElement (永远不要低估一个好名字的澄清能力):

hasElement x [] = NoDuplicateFound
hasElement x (y:ys) = if x == y then DuplicateFound x
                                else hasElement x ys

Then: 然后:

findDuplicate [] = NoDuplicateFound
findDuplicate (x:xs) = 
    case hasElement x xs of
        DuplicateFound dup -> ...
        NoDuplicateFound   -> ...

I will leave you to fill in the ... s. 我会让你填写... s。 Good luck, and thank you for attempting a solution before coming here for help. 祝你好运,感谢你在来这里寻求帮助前尝试解决方案。 It makes me more willing to put effort into my answer. 这让我更愿意为我的答案付出努力。

You can easily (but not very efficiently), get a list of all the duplicates using nub and (\\\\) . 您可以轻松(但不是非常有效),使用nub(\\\\)获取所有重复项的列表。

I presume this is a homework: this suggestion should give you a good starting point. 我认为这是一个功课:这个建议应该给你一个很好的起点。

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

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