1

I am new to Haskell and I am trying to understand it. Now I'm reading about lists and I have some questions, how to:

  1. Remove duplicate sub-lists from a list?
  2. Count the number of duplicate items in a list?
1
  • Sounds a bit like homework? ... Can you define what you need to know in order to solve your problems? Commented Mar 26, 2011 at 14:47

4 Answers 4

1
countItems item = length . filter (item==) 

For the first questions I believe there is a standard function called nub

Sign up to request clarification or add additional context in comments.

Comments

1
  1. nub

  2. This question isn't very well specified, maybe you mean this:

    ndups xs = length xs - length (nub xs) 

Comments

0

about "nub" and my first question:

nub [1,2,3,1] 

will return [1,2,3]

but i need: "smth" [3,7] [1,3,7,2,4,3,5,3,7] = [1,2,4,3,5].

i know about

(\\) [3,7] [1,3,7,2,4,3,5,3,7] 

but it works only for first sublist [3,7]

[1,2,4,3,5,3,7] 

3 Comments

You can edit your original post to add this kind of information.
I am afraid your terminology (sublist) does not match what you show here - I see only lists of integers, not lists of lists. If you want to remove all elements of the first list "first" from the second one "second" use (filter (flip notElem first) second)
You are right! Sorry, in fact, my terminology (sublist) is incorrect. My example [3,7] [1,3,7,2,4,3,5,3,7] = [1,2,4,3,5] is wrong, i really need [[1,2],[3,5,7],[1,8,1,9],[1,2],[1,2],[3,5,7]] = [[1,2],[3,5,7],[1,8,1,9]] and "nub" will be enough for it
0

Sub-list can have different meaning [3,7] is a contiguous sub-list of [1,3,7,8], and also a non-contiguous sub-list of [3,1,7]

If you mean contiguous sub-list then you should look into isPrefixOf in Data.List.

With it you can iterate through the list, removing each of the sub-lists like so:

import Data.List

(//) :: (Eq a) => [a] -> [a] -> [a]

(//) rem [] = []

(//) rem list = if (isPrefixOf rem list)

 then [your code here] else [your code here] 

How do you want to handle this case:

(//) [3,7] [3,3,3,7,7,7]

when we remove the sub-list in the middle we will create a new sub-list, should this be removed or not?

If they also should be removed then you can instead build your list with the help of a foldr. You can implement a function that gives the result below by specifying a helper function remPrefix and then building the list up from the end, removing sub-lists as they are formed.

*Main> (//) [1,2] [1,2,4,5,1,1,2,2,3,4]

[4,5,3,4]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.