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


Groups > comp.lang.forth > #52977

Re: :Re: My LOOP is ugly

From Melzzzzz <mel@zzzzz.com>
Newsgroups comp.lang.forth
Subject Re: :Re: My LOOP is ugly
Date 2016-11-30 06:35 +0100
Organization albasani.net
Message-ID <20161130063555.3d621465@maxa-pc> (permalink)
References <o1h2gm$qse$1@gioia.aioe.org>

Show all headers | View raw


On Mon, 28 Nov 2016 10:56:23 +0000 (UTC)
"Robert L." <No_spamming@noWhere_7073.org> wrote:

> Kenny Tilton wrote:
> 
> > (defun p2b (pairs &key ((:test test) #'eql))
> >    "((A 1) (A 2) (B 2) (C 2) (C 3)) ==> ((A 1 2) (B 2) (C 2 3))"
> >    (loop with bunch = nil
> >          for (one two) in pairs
> >          do (push two (cdr (or (assoc one bunch :test test)
> >                              (car (push (list one) bunch)))))
> >          finally (return bunch)))  
> 
> Testing:
> 
> * (p2b '((A 1) (A 2) (B 2) (C 2) (C 3)))
> 
> ((C 3 2) (B 2) (A 2 1))
> 
> Ruby:
> 
> def p2b(pairs)
>   pairs.group_by{|k,v|
>     block_given? ? yield(k) : k
>   }.map{|k,v| [k, *v.map(&:last)]}
> end
> 
> p2b [[:A,1], [:A,2], [:B,2], [:C,2], [:C,3]]
>  ===>  
> [[:A, 1, 2], [:B, 2], [:C, 2, 3]]
> 
> 
> p2b([['Foo',2],['bar',4],['foo',22],['BAR',44]]){|s| s.downcase}
>  ===>  
> [["foo", 2, 22], ["bar", 4, 44]]
> 
> 
> In Forth?
> 
Haskell:

import Data.List (groupBy,sort)
import Data.Char (toUpper)
p2b :: (Eq a,Ord a,Ord b)=>[(a,b)]->[(a,[b])]
p2b = let f :: [(a,b)] -> (a,[b])
          f x = foldl (\(a,b) (_,y) -> (a,y:b)) (fst.head $ x,[snd.head $ x]) (tail x)
          in map (\x->(fst $ f x,sort.snd $ f x))
            . groupBy (\x y-> fst x == fst y ) . sort 
main = do
    print $ p2b [('C',3),('A',1),('B',2),('A',2),('C',2)]
    print $ p2b $ map (\(x,y)->(map toUpper x,y)) 
                 [("bar",44),("Foo",2),("foo",22),("BAR",4)]

[bmaxa@maxa-pc WJ]$ ./pairs
[('A',[1,2]),('B',[2]),('C',[2,3])]
[("BAR",[4,44]),("FOO",[2,22])]

-- 
press any key to continue or any other to quit

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


Thread

:Re: My LOOP is ugly "Robert L." <No_spamming@noWhere_7073.org> - 2016-11-28 10:56 +0000
  Re: :Re: My LOOP is ugly trans <transfire@gmail.com> - 2016-11-28 06:37 -0800
  Re: :Re: My LOOP is ugly Melzzzzz <mel@zzzzz.com> - 2016-11-30 06:35 +0100
    Re: :Re: My LOOP is ugly Paul Rubin <no.email@nospam.invalid> - 2016-11-29 23:31 -0800
      Re: :Re: My LOOP is ugly Melzzzzz <mel@zzzzz.com> - 2016-11-30 08:59 +0100

csiph-web