Count elements on ordered list

ordered list html mdn
ol type= a start= b
ordered list html example
ordered and unordered list in html example
the reverse attribute allows a list to appear in a reverse order in an unordered list.
which attribute can be used to change its number within an ordered list?
the start attribute defines the number from which an unordered list should start.
list element

I want to do a Haskell function where the input (a list of Strings) is ordered (always. input is valid only if is ordered) and I want to get the number of occurrences of each different string.

Example:

ContaOcs["a", "a", "b", "c", "c", "c", "d"]

Should return:

[(2,"a"), (1,"b"), (3,"c"), (1,"d")]

Here is What I'm trying to do:

module Main where

contaOcs :: [String] -> [(Int, String)]
contaOcs [] = [_,_]
contaOcs [x] = [1,x]
contaOcs (i, x1:x2:xs)
 | x1 == x2 =  (i+1,(x2:xs))
 | otherwise = (0, (x2:xs))

But this code have some errors and I'm not so sure how I should do to accomplish this I'm new to functional programing and Haskell. Can anyone help me with some information?

Thanks for any help.

There are some syntactical problems as well as problems with the types. The first line looks like:

contaOcs [] = [_,_]

But an underscore (_) in the result does not makes any sense, you can only construct lists with values in it. When we count the number of occurences of an empty list, the result will be an empty list, so contaOcs [] = [].

As for the second:

   contaOcs [x] = [1,x]

Here you aim to return a list with two elements: a 1 and an x (which is a String). In Haskell the elements of a list all have the same type. What you can do is return a list of 2-tuples with the first item an Int, and the second a String, like the signature suggests, but then you need to wrap the values in a 2-tuple, like contaOcs [x] = [(1,x)].

In your last clause, you write:

contaOcs (i, x1:x2:xs) = ...

which does not make much sense: the input type is a list (here of Strings), not a 2-tuple with an Int, and a list of strings.

So the input will look like:

contaOcs (x1:x2:xs) = ...

The output, like (i+1,(x2:xs)) also is not in "harmony" with the proposed output type in the signature, this looks like a 2-tuple with an Int, and a list of Strings, so (Int, [String]), not [(Int, String)].

Based on the above comments, we have derived something like:

contaOcs :: [String] -> [(Int, String)]
contaOcs [] = []
contaOcs [x] = [(1,x)]
contaOcs (x1:x2:xs)
     | x1 == x2 =  -- ...
     | otherwise = -- ...

So now there are two parts to fill in. In case x1 and x2 are not equal, that means that we can first yield a tuple (1, x1) in the list, followed by the result of contaOcs on the rest of the list (x2 included), so:

(1, x1) : contaOcs (x2:xs)

In the latter case, it means that we first make a recursive call to contaOcs with (x2:xs), and then increment the counter of the first item of that list. We are sure such element exists, since we make a recursive call with a list containing at least one element, and by induction, that means the result contains at least one element as well, since the base case contains one element, and the recursive case either prepends elements to the result, or updates these.

So we can use a pattern guard, and maniplate the result, like:

contaOcs :: [String] -> [(Int, String)]
contaOcs [] = []
contaOcs [x] = [(1,x)]
contaOcs (x1:x2:xs)
     | x1 == x2, ((yi, yv):ys) <- contaOcs (x2:xs) = (yi+1, yv) : ys
     | otherwise = (1, x1) : contaOcs (x2:xs)

We can also use an "as-pattern": we only need a reference to the tail of the list starting with x2, not xs:

contaOcs :: [String] -> [(Int, String)]
contaOcs [] = []
contaOcs [x] = [(1,x)]
contaOcs (x1:xs@(x2:_))
     | x1 == x2, ((yi, yv):ys) <- contaOcs xs = (yi+1, yv) : ys
     | otherwise = (1, x1) : contaOcs xs

The above is however not very elegantly. It might be better to use an accumulator here, I leave this as an exercise.

<ol>: The Ordered List element, This Boolean attribute specifies that the list's items are in reverse order. Items will be numbered from high to low. start: An integer to start counting  When we count the number of occurences of an empty list, the result will be an empty list, so contaOcs [] = []. As for the second: contaOcs [x] = [1,x] Here you aim to return a list with two elements: a 1 and an x (which is a String). In Haskell the elements of a list all have the same type.

Let's look at some of the errors mentioned by ghc. Always pay close attention to when GHC talks about Expected and Actual types, as these messages are always illuminating. Expected indicates what GHC thinks you should write. Actual indicates what you wrote. You either need to change what you wrote (read: change your code), or change what GHC thinks you should write (read: change your type annotations). In this case it's mostly the former.

hw.hs:2:16: error:
    • Found hole: _ :: (Int, String)
    • In the expression: _
      In the expression: [_, _]
      In an equation for ‘contaOcs’: contaOcs [] = [_, _]
    • Relevant bindings include
        contaOcs :: [String] -> [(Int, String)] (bound at hw.hs:2:1)
  |
2 | contaOcs [] = [_,_]
  |                ^

hw.hs:2:18: error:
    • Found hole: _ :: (Int, String)
    • In the expression: _
      In the expression: [_, _]
      In an equation for ‘contaOcs’: contaOcs [] = [_, _]
    • Relevant bindings include
        contaOcs :: [String] -> [(Int, String)] (bound at hw.hs:2:1)
  |
2 | contaOcs [] = [_,_]
  |                  ^

The underscore is used as a placeholder (or "hole"), to be filled in later. GHC is telling you that you should figure out something to put in these holes.

hw.hs:3:19: error:
    • Couldn't match type ‘[Char]’ with ‘(Int, String)’
      Expected type: (Int, String)
        Actual type: String
    • In the expression: x
      In the expression: [1, x]
      In an equation for ‘contaOcs’: contaOcs [x] = [1, x]
  |
3 | contaOcs [x] = [1,x]
  |

You have declared that the return type of the function is [(Int, String)], in other words, a List, where each element of the list is a Tuple of Int and String.

Therefore, each element in the list should be a Tuple. The syntax [1,x] means a list with two elements: 1 and x. GHC has noticed that x, however, is known to be a String, which is not a Tuple. (GHC failed to notice that 1 is not a tuple, for... reasons. Numbers in Haskell are a little weird and GHC is not so helpful with those.)

Perhaps you meant to write (1, x), which is a tuple of 1 (an Int) and x (a String). However, don't forget to also put that tuple into a list somehow, since your return type is a list of tuples.

hw.hs:4:10: error:
    • Couldn't match expected type ‘[String]’
                  with actual type ‘(Integer, [a0])’
    • In the pattern: (i, x1 : x2 : xs)
      In an equation for ‘contaOcs’:
          contaOcs (i, x1 : x2 : xs)
            | x1 == x2 = (i + 1, (x2 : xs))
            | otherwise = (0, (x2 : xs))
  |
4 | contaOcs (i, x1:x2:xs)
  |          ^^^^^^^^^^^^^

GHC is again reminding you that it expects a list of tuples, but in this case, you gave it just one tuple.

The errors are mostly the same as this.

Python count items in list, Python how to count elements of a list: Count elements in ordered list; Count elements in unordered list  This is a list of the 118 chemical elements which have been identified as of 2019. A chemical element, often simply called an element, is a species of atoms which all have the same number of protons in their atomic nuclei. A popular visualization of all 118 elements is the periodic table of the elements, a convenient tabular arrangement of the elements by their chemical properties that uses abbreviated chemical symbols in place of full element names, but the simpler list format presented here ma

contaOcs ::  [String] -> [(Int, String)]

contaOcs consumes a list of strings: xss, for each unique string: xs in xss, we produce a pair: p, whose first element represents the number of occurrences of xs in xss, and the second element of p is that xs itself.

We know we need to group strings by their uniqueness and count each unique string's total occurrences. You can follow this idea and implement the rest yourself. contaOcs takes a list and produces a new list so list comprehension should give you what you want. You're transforming one list to another, so fmap a function that accumulates should work. You can also just use natural recursion or accumulator. Here is one way to write contaOcs:

contaOcs = (return . liftA2 (,) length head =<<) . group  

Write down the signature, purpose statement, some sample data and test cases first, then it's just a matter of finding the solutions that best fit your need.

Number of Ways to Make An Ordered List Or A Group, Here order counts. A list is required. For a source set of n elements, if order is important and x elements are chosen for the ordered list, a permutation of n things  @KritikaRajain For each unique element in the list you iterate over the whole list to generate a count (quadratic in the number of unique elements in the list). Instead, you can iterate over the list once and count up the number of each unique element (linear in the size of the list).

This is a good example of when a co-recursive function is helpful.

contaOcs :: [String] -> [(Int, String)]

We'll define contaOcs as the outer function that takes the list of strings and returns the tuples. First let's look at the trivial cases:

contaOcs [] = []
contaOcs [x] = [(1,x)]

Pass an empty list, and you should get back an empty list. Pass a single element list, and you should get back a list with one element: (1, x). Now we can guarantee that any other list is 2+ elements long.

contaOcs (x:xs) = go x xs

go? What is go you might ask? Well let's define it in the where clause:

  where
  go cur xs = let (this, rest) = span (==x) xs
              in (succ . length $ this, cur) : contaOcs diff

That's kind of a lot, so let's unpack. go is an idiomatic term for a function helper (this could as easily be named f or frobnicator, it doesn't matter). It takes the character we're counting, which is split separately from the rest of its list, and calls it x. It runs a span (==x) against the rest of the list, which splits it into a tuple (longestPrefixThatMatches, rest). We return the length of that longest prefix (plus one, since we've stripped off the front character) paired with the character itself in a tuple, then cons that with the recursive case -- handing the rest of the list back to the outer function to handle.

jQuery: Count the number of specific elements, jQuery Events : Exercise - 22 with Solution. Count the number of specific elements. HTML code: <body> <ul> <li>List - 1</li> <li>List - 2</li>  HTML Ordered List or Numbered List displays elements in numbered format. The HTML ol tag is used for ordered list. The HTML ol tag is used for ordered list. We can use ordered list to represent items either in numerical order format or alphabetical order format, or any format where an order is emphasized.

What you want can be done by a one-liner

Prelude> import Data.List
Prelude Data.List> ls = ["a", "a", "b", "c", "c", "c", "d"]
Prelude Data.List> [(length x, head x) | x <- group ls]
[(2,"a"),(1,"b"),(3,"c"),(1,"d")]

I mix list comprehension with the group function. Basic concepts you can make yourselves familiar with.

Fundamentals of Computer-Aided Engineering, From experience , we know that searching in an ordered list is much simpler Since there is an even number of elements in this list , take the last element in the​  Typically, ordered list items display with a preceding marker, such as a number or letter. The <ol> and <ul> elements may nest as deeply as desired, alternating between <ol> and <ul> however you like. The <ol> and <ul> elements both represent a list of items. The difference is with the <ol> element, the order is meaningful.

Python Lists, Tuple is a collection which is ordered and unchangeable. You access the list items by referring to the index number: Print the number of items in the list:. Each element is identified by the number of protons in its atoms. This number is the atomic number. The periodic table lists the elements in order of increasing atomic number. Each element has a symbol, which is one or two letters. The first letter is always capitalized. If there is a second letter, it is lowercase.

OrderedList, Iterator<E>, iterator() Construct an iterator for traversing elements of ordered list in ascending order count. protected int count. Number of elements in list  A description list is a list of terms, with a description of each term. The <dl> tag defines the description list, the <dt> tag defines the term (name), and the <dd> tag describes each term: Example

Discrete Mathematics, Hence the total number of sequences of two elements from a 4—element set is 4 - 3 I 12. Q More generally, if we are seeking the number of ordered lists of r  To create a count of the values that appear in in a list or table, you can use the COUNTIFS function. In the example shown, the formula in D5 is: The COUNTIFS function takes range/criteria pairs, and delivers a count when all criteria match. This example, contains two range/criteria pairs. In pair 1, the range is B:B (entered as a full column

Comments
  • Probably a duplicate. Anyway the linked question mentions (in the question itself) an answer to this question. How to group similar items in a list using Haskell?
  • near dup: stackoverflow.com/questions/48669774/…
  • EDIT: Thanks everyone for the help. More then 1 answer solves the problem. I up-voted all good answers.
  • Thanks. This answer is the most complete one.
  • Should be (length x, head x) from the OP's description, and you should add some explanation (or at the very least, pointers to docs on list comprehensions and the group function) (downvote's not mine, with small improvements this can be a good answer).
  • this was a good answer even in its first version. the swapping of the tuple is not important, and even good to cause the OP to pay attention. (-2) for that?? I don't understand this. ---- BTW another way of writing it is map (length &&& head) . group, which is all there is to it.
  • @Redu almost. :) but first: for me, . is immediately clear, but with <$> I need to think it over to understand which instance it is... and here too you might have thought it's map (I did, at first, before I checked the type), but it's actually .. your code is equivalent to liftA2 (,) length head . group :: Eq b => [b] -> [(Int, b)] but we need map (liftA2 (,) length head) . group :: Eq b => [b] -> [(Int, b)]. writing it as (liftA2 (,) length head <$>) <$> group would only be an extreme obfuscation, IMO. :)
  • @Redu I had a typo there, which thwarted the whole point of my remark. your code's type is Eq b => [b] -> (Int, [b]) (I copied the wrong thing from the GHCi window). It calculates an entirely different result.
  • @Will Ness Yes i've got your point. It should be like ((,) <$> length <*> head <$>) <$> group due to the nested functures. Thanks for correcting.
  • removed the [x] case
  • does take 2 . contaOcs $ ["a","b"] ++ repeat "c" work? :)