Stanislau
Stanislau

Reputation: 432

Lists in Haskell

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?

Upvotes: 1

Views: 542

Answers (4)

Aune
Aune

Reputation: 1

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]

Upvotes: 0

Stanislau
Stanislau

Reputation: 432

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]

Upvotes: 0

augustss
augustss

Reputation: 23004

  1. nub

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

    ndups xs = length xs - length (nub xs)
    

Upvotes: 1

Ingo
Ingo

Reputation: 36329

countItems item = length . filter (item==)

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

Upvotes: 1

Related Questions