Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #24137

Re: Simple problem

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.forth
Subject Re: Simple problem
Date 2013-07-04 03:24 +0000
Organization A noiseless patient Spider
Message-ID <kr2pt0$e2q$1@dont-email.me> (permalink)
References <kgs058018sm@enews4.newsguy.com>

Show all headers | View raw


WJ wrote:

> 
> Given a list of strings, count the number of times each string
> occurs.  Sort the result from most to least common.
> 
> Factor:
> 
> 
> USING: locals ;
> 
> :: counts ( seq -- seq )
>   H{ } clone :> table
>   seq [ table inc-at ] each
>   table >alist [ [ last ] bi@  swap  <=> ] sort
>   dup .
> ;
> 
> { "c" "c" "a" "b" "b" "c" } counts
> 
> { { "c" 3 } { "b" 2 } { "a" 1 } }

OCaml:

let update_tbl tbl s =
  if Hashtbl.mem tbl s then
    Hashtbl.replace tbl s ((Hashtbl.find tbl s) + 1)
  else
    Hashtbl.add tbl s 1 ;;

let counts s_list =
  let tbl = Hashtbl.create 99 in
    ( List.iter (fun s -> update_tbl tbl s) s_list;
      List.sort (fun x y -> (snd y) - (snd x))
        (Hashtbl.fold (fun k v acc -> (k,v):: acc) tbl [])
    ) ;;


counts ["a";"b";"a";"c";"c";"c"];;
 ==> [("c", 3); ("a", 2); ("b", 1)]

Back to comp.lang.forth | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-03-02 04:45 +0000
  Re: Simple problem Doug Hoffman <glidedog@gmail.com> - 2013-03-02 06:16 -0500
  Re: Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-03-18 05:41 +0000
    Re: Simple problem albert@spenarnc.xs4all.nl (Albert van der Horst) - 2013-03-18 11:23 +0000
    Re: Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-06-15 00:53 +0000
      Re: Simple problem visualforth@rocketmail.com - 2013-06-21 20:14 -0700
        Re: Simple problem glidedog@gmail.com - 2013-06-22 06:01 -0700
          Re: Simple problem rickman <gnuarm@gmail.com> - 2013-06-22 09:48 -0400
          Re: Simple problem Bernd Paysan <bernd.paysan@gmx.de> - 2013-06-22 22:55 +0200
            Re: Simple problem "Elizabeth D. Rather" <erather@forth.com> - 2013-06-22 11:47 -1000
  Re: Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-04-02 08:22 +0000
  Re: Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-07-04 03:24 +0000
    Re: Simple problem Paul Rubin <no.email@nospam.invalid> - 2013-07-03 21:32 -0700
  Re: Simple problem "WJ" <w_a_x_man@yahoo.com> - 2013-07-04 10:03 +0000

csiph-web