Sophia List How do I count duplicates

I have a List right now
Its data content looks like this


We can see that 0 appears the most often. How can we implement this programmatically?
For example, how can I get which number in the List is repeated the most through Sophia?
I don’t know how to write it because Sophia doesn’t define temporary variables.

1 Like

My teacher, I need your help again :grin:


Something like this perhaps:

contract C =
  entrypoint most_of((x :: xs) : list('a)) : 'a * int =
    most_of_(x, {[x] = 1}, xs)

  function most_of_(most : 'a, counts : map('a, int), xs : list('a)) =
      [] => (most, counts[most])
      (x :: xs) =>
        let counts' = counts{ [x = 0] @ n = n + 1 }
        if (counts'[x] >= counts'[most]) 
          most_of_(x, counts', xs) 
          most_of_(most, counts', xs)

It will return the most occurring element and its count. Note that it will crash if the list is empty, but that can be amended.

Thank you very much.
This part of the code is out of my depth and I need to digest it
(x :: xs)
I don’t quite understand what this grammar means. You need to understand that

It means matching the list and splitting it into its “head” (first element) x and its “tail” (the rest of the elements) xs

Okay, I’ll look into it. Thank you :grin:

Yes, that is how I tested it (this testing function accepts a list of arguments, hence the extra []):

([email protected])17> aefa_sophia_test:run_file("/tmp/most_of.aes", "most_of", [[1, 2, 2, 1, 3, 5, 4, 4, 1, 2, 4, 2]]).
177 steps / 1872 gas / 7264 reductions / 0.23ms

I love you :heart_eyes: :smile: