Arc Forumnew | comments | leaders | submitlogin
1 point by waterhouse 4886 days ago | link | parent

Function: (count-up xs) : Returns a list of lists of the form (x n), where x is an element of xs and n is the number of times x occurs in xs. This list is sorted to present most frequent items first (otherwise it would be sorted pseudorandomly).

  arc> (count-up "banana")
  ((#\a 3) (#\n 2) (#\b 1))
  arc> (factor 720)
  (2 2 2 2 3 3 5)
  arc> count-up.that
  ((2 4) (3 2) (5 1))
Useful for, well, counting things up; I've used this to count word and letter frequencies, calculate the totient function, create a couple of histograms, compute the number of distinct permutations of a list, help print out a number's prime factorization, test the randomness of supposedly random functions, and do some other things.

  (def count-up (xs)
    (let u (table)
      (each x xs
        (++ (u x 0)))
      (sort (compare > cadr) (tablist u))))


2 points by fallintothis 4886 days ago | link

Ah, that's a fun one. Could use counts to get a table in vanilla Arc, except that it hard-codes recursion on cdrs, so it won't work for strings. From arc.arc:

  (def counts (seq (o c (table)))
    (if (no seq)
        c
        (do (++ (c (car seq) 0))
            (counts (cdr seq) c))))
It's also easy to not notice the built-in sortable from srv.arc:

  (def sortable (ht (o f >))
    (let res nil
      (maptable (fn kv
                  (insort (compare f cadr) kv res))
                ht)
      res))
So,

  (= count-up (compose sortable counts [coerce _ 'cons]))
until counts gets fixed to use each, at which point it's just

  (= count-up sortable:counts)

-----

1 point by akkartik 4886 days ago | link

Ah, getting rid of the optional arg lets me define counts using defgeneric!

I've updated my repo with your suggestions: https://github.com/akkartik/arc/commit/a5b3c6d6bf616f51bc4ab...

-----

1 point by akkartik 4886 days ago | link

Hey, I call this freq. Nice to meetcha.

-----