COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### toy list processing problem: collect similar terms

• Follow

```here's a interesting toy list processing problem.

I have a list of lists, where each sublist is labelled by
a number. I need to collect together the contents of all sublists
sharing
the same label. So if I have the list

((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
r) (5 s t))

where the first element of each sublist is the label, I need to
produce:

output:
((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

a Mathematica solution is here:
http://xahlee.org/UnixResource_dir/writ/notations_mma.html

R5RS Scheme lisp solution:
http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gmail.=
scm
by Sourav Mukherjee

also, a Common Lisp solution can be found here:
c750b?

anyone care to give a solution in Python, Perl, javascript, or other
lang? am guessing the scheme solution can be much improved... perhaps
using some lib but that seems to show scheme is pretty weak if the lib
is non-standard.

Xah =E2=88=91 xahlee.org =E2=98=84
```
 0
Reply xahlee (818) 9/26/2010 4:05:13 AM

```On 09/25/2010 09:05 PM, Xah Lee wrote:
> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> a Mathematica solution is here:
> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> R5RS Scheme lisp solution:
> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gm=
ail.scm
> by Sourav Mukherjee
>
> also, a Common Lisp solution can be found here:
824bc750b?
>
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.
>
>   Xah =E2=88=91 xahlee.org =E2=98=84
>   =20

Python 3:  (I have not tried to match the exact format of your output,=20
but I get the right things is the right order.)

data =3D ((0,'a','b'), (1,'c','d'), (2,'e','f'), (3,'g','h'),
(1,'i','j'), (2,'k','l'), (4,'m','n'), (2,'o','p'),
(4,'q','r'), (5,'s','t'))

from collections import OrderedDict
r =3D OrderedDict()
for label,*rest in data:
r.setdefault(label, []).extend(rest)
print(list(r.values()))

produces:

(['a', 'b'], ['c', 'd', 'i', 'j'], ['e', 'f', 'k', 'l', 'o', 'p'], ['g', =

'h'], ['m', 'n', 'q', 'r'], ['s', 't'])

--=20
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

```
 0
Reply gherron1 (37) 9/26/2010 5:21:48 AM

```In PicoLisp:

(mapcar
'((X) (apply conc (cdr X)))
(group List) )

Cheers,
- Alex
```
 0

```Python solution follows.  Removed all crossposts since massive
crossposting is a standard trolling tactic.

from collections import defaultdict

def collect(xss):
d = defaultdict(list)
for xs in xss:
d[xs[0]].extend(xs[1:])
return sorted(v for k,v in d.items())

y = [['0','a','b'], ['1','c','d'], ['2','e','f'], ['3','g','h'],
['1','i','j'], ['2','k','l'], ['4','m','n'], ['2','o','p'],
['4','q','r'], ['5','s','t']]

print collect(y)
```
 0

```Python solution follows (earlier one with an error cancelled).  All
crossposting removed since crossposting is a standard trolling tactic.

from collections import defaultdict

def collect(xss):
d = defaultdict(list)
for xs in xss:
d[xs[0]].extend(xs[1:])
return list(v for k,v in sorted(d.items()))

y = [[0,'a','b'], [1,'c','d'], [2,'e','f'], [3,'g','h'], [1,'i','j'],
[2,'k','l'], [4,'m','n'], [2,'o','p'], [4,'q','r'], [5,'s','t']]

print collect(y)
```
 0

```Here is mine for Python:

l = [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
[5, 's', 't']]
d = {}
for idx, items in [(e[0], e[1:]) for e in l]: d[idx] = d[idx] + items
if idx in d else items
print d.values()

Output:
[['a', 'b'], ['c', 'd', 'i', 'j'], ['e', 'f', 'k', 'l', 'o', 'p'],
['g', 'h'], ['m', 'n', 'q', 'r'], ['s', 't']]
```
 0

```On 26 Sep, 08:47, livibetter <livibet...@gmail.com> wrote:
> Here is mine for Python:
>
> l = [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
> 'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
> [5, 's', 't']]
> d = {}
> for idx, items in [(e[0], e[1:]) for e in l]: d[idx] = d[idx] + items
> if idx in d else items
> print d.values()
>
> Output:
> [['a', 'b'], ['c', 'd', 'i', 'j'], ['e', 'f', 'k', 'l', 'o', 'p'],
> ['g', 'h'], ['m', 'n', 'q', 'r'], ['s', 't']]

from itertools import groupby
from operator import itemgetter

l = [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q',
'r'],
[5, 's', 't']]

[
[x for g in gs for x in g[1:]]
for _, gs in groupby(sorted(l), itemgetter(0))
]

--
Arnaud
```
 0

```On 2010-09-26 06:05, Xah Lee wrote:

> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

The input is a string on STDIN,
and the output is a string on STDOUT?

Use a hash:

perl -MData::Dumper -wle '\$Data::Dumper::Sortkeys = 1;
my \$t = "((0 a b) (1 c d) (2 e f) (3 g h) (1 i j)"
. " (2 k l) (4 m n) (2 o p) (4 q r) (5 s t))";

push @{ \$h{ \$1 } }, \$2 while \$t =~ /(\w+)([^)]*)/g;  # gist

print Dumper \%h;
'

or an array:

perl -wle '
my \$t = "((0 a b) (1 c d) (2 e f) (3 g h) (1 i j)"
. " (2 k l) (4 m n) (2 o p) (4 q r) (5 s t))";

push @{\$a[\$1]},\$2 while \$t =~ /(\w+)\s+([^)]*)/g; # gist.1
print "((".join(") (",map join(" ",@\$_),@a )."))";  # gist.2
'

Or if the list is not just a string, but a real data structure in the
script:

perl -wle'
my \$t = [ [qw/0 a b/], [qw/1 c d/], [qw/2 e f/], [qw/3 g h/],
[qw/1 i j/], [qw/2 k l/], [qw/4 m n/], [qw/2 o p/],
[qw/4 q r/], [qw/5 s t/] ];

push @{ \$a[ \$_->[0] ] }, [ @\$_[ 1, 2 ] ] for @\$t;  # AoAoA

printf "((%s))\n", join ") (",
map join( " ",
map join( " ", @\$_ ), @\$_
), @a;
'

Etc.

--
Ruud

```
 0

```Alexander Burger <abu@software-lab.de> wrote:
>In PicoLisp:

What the f**** does PicoLisp have to with Perl?

jue
```
 0

```livibetter <livibetter@gmail.com> wrote:
>Here is mine for Python:

What the f*** does Python have to do with Perl?

jue
```
 0

```Xah Lee <xahlee@gmail.com> writes:

> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> a Mathematica solution is here:
> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> R5RS Scheme lisp solution:
> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gmail.scm
> by Sourav Mukherjee
>
> also, a Common Lisp solution can be found here:

It's too complex. Just write:

(let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
(2 o p) (4 q r) (5 s t))))

(mapcar (lambda (class) (reduce (function append) class :key (function rest)))
(com.informatimago.common-lisp.list:equivalence-classes list :key (function first)))

)

--> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))

--
__Pascal Bourguignon__                     http://www.informatimago.com/
```
 0

```In comp.lang.lisp Pascal J. Bourguignon <pjb@informatimago.com> wrote:
> It's too complex. Just write:
> ...
>  (mapcar (lambda (class) (reduce (function append) class :key (function rest)))
>           (com.informatimago.common-lisp.list:equivalence-classes list :key (function first)))

Still too complex! ;-)
```
 0

```Jürgen Exner <jurgenex@hotmail.com> writes:

> Alexander Burger <abu@software-lab.de> wrote:
>>In PicoLisp:
>
> What the f**** does PicoLisp have to with Perl?

It's Xah. He cross-posts in an attempt to start a language feud.

sherm--

--
Sherm Pendley
<http://camelbones.sourceforge.net>
Cocoa Developer
```
 0

```Jürgen Exner <jurgenex@hotmail.com> writes:

> livibetter <livibetter@gmail.com> wrote:
>>Here is mine for Python:
>
> What the f*** does Python have to do with Perl?

Xah is a cross-posting troll. Please don't feed the troll.

sherm--

--
Sherm Pendley
<http://camelbones.sourceforge.net>
Cocoa Developer
```
 0

```Quoth pjb@informatimago.com (Pascal J. Bourguignon):
>
> It's too complex. Just write:
>
> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
>               (2 o p) (4 q r) (5 s t))))

Unless you're going to talk about Perl, please take clpmisc out of the
xpost.

Ben

```
 0

```Jürgen Exner <jurgenex@hotmail.com> writes:

> livibetter <livibetter@gmail.com> wrote:
>>Here is mine for Python:
>
> What the f*** does Python have to do with Perl?

Clueless fuck. I unsubscribed from comp.lang.perl.misc to avoid the
retards like you and now you come in via the backdoor. If you have a
problem with Xah report him with Google Groups and with his hosting
provider 1&1 like I do. Dreamhost kicked him out that way.

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0

```2010-09-26

On Sep 25, 11:17=C2=A0pm, Paul Rubin <no.em...@nospam.invalid> wrote:
> Python solution follows (earlier one with an error cancelled). =C2=A0All
> crossposting removed since crossposting is a standard trolling tactic.
>
> =C2=A0 =C2=A0 from collections import defaultdict
>
> =C2=A0 =C2=A0 def collect(xss):
> =C2=A0 =C2=A0 =C2=A0 =C2=A0 d =3D defaultdict(list)
> =C2=A0 =C2=A0 =C2=A0 =C2=A0 for xs in xss:
> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 d[xs[0]].extend(xs[1:])
> =C2=A0 =C2=A0 =C2=A0 =C2=A0 return list(v for k,v in sorted(d.items()))
>
> =C2=A0 =C2=A0 y =3D [[0,'a','b'], [1,'c','d'], [2,'e','f'], [3,'g','h'], =
[1,'i','j'],
> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0[2,'k','l'], [4,'m','n'], [2,'o','p'], =
[4,'q','r'], [5,'s','t']]
>
> =C2=A0 =C2=A0 print collect(y)

Hi Paul,

thanks for your solution, and thanks to many other who provided
solutions. It'll take some time to go thru them.

interested, you can read in the following:

=E2=80=A2 =E3=80=88Cross-posting &amp; Language Factions=E3=80=89
http://xahlee.org/Netiquette_dir/cross-post.html

that.

i'll go over the solutions and post if i have anything interesting to
say. =E2=98=BA Possbly will select some to show on my site with credit of
course.

Xah =E2=88=91 xahlee.org =E2=98=84
```
 0
Reply xahlee (818) 9/26/2010 8:56:52 PM

```On Sep 26, 7:56=C2=A0am, Sherm Pendley <sherm.pend...@gmail.com> wrote:
> J=C3=BCrgen Exner <jurge...@hotmail.com> writes:
> > Alexander Burger <a...@software-lab.de> wrote:
> >>In PicoLisp:
>
> > What the f**** does PicoLisp have to with Perl?
>
> It's Xah. He cross-posts in an attempt to start a language feud.
>
> Please don't feed the troll.

sorry i disagree. And please don't randomly accuse... I posted the
following in reply to Paul Rubin's very valuable post, to
comp.lang.python only. But since you cross-posted your accusation, and
there are about 3 other posts of similar nature accusing me cross-
posted to all groups, so am posting a response to all groups too.

--------------------------------------------------
Paul,

....

interested, you can read in the following:

=E2=80=A2 =E3=80=88Cross-posting &amp; Language Factions=E3=80=89
http://xahlee.org/Netiquette_dir/cross-post.html

that.

i'll go over the solutions and post if i have anything interesting to
say. =E2=98=BA Possbly will select some to show on my site with credit of
course.

Xah =E2=88=91 xahlee.org =E2=98=84
```
 0

```On 9/25/10 9:05 PM, Xah Lee wrote:
> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
...
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.

In Q (from kx.com)[1]:

x:((0; "a"; "b");(1; "c"; "d");(2; "e"; "f");(3; "g"; "h");(1; "i"; "j")
(2; "k"; "l");(4; "m"; "n");(2; "o"; "p");(4; "q"; "r");(5; "s"; "t"))
f:{each [,/] each [each [1 _]] x @ value group x[;0]}
f x

outputs

"ab"
"cdij"
"efklop"
"gh"
"mnqr"
"st"

Note that this is actually a pretty general solution in that *all*
the functions used in it operate on a variety of types.
- The label could be anything, not just an integer.
- What follows a label can be a list of anything.
- Everything, except for = (the group function), has to do with
*shaping* the output in the way you want. It is all basically
cut-n-paste or pulling apart your Lego blocks and constructing
a new toy from them! And most languages are really poor at that.
*This* is why proponents of various languages should pay attention
to such problems.

----
[1] In k3 (an older language from kx.com that you may be able to find
online), x is the same but f is as follows:

f:{,/'1_''x@=x[;0]}
```
 0

```John Bokma <john@castleamber.com> wrote:
>J�rgen Exner <jurgenex@hotmail.com> writes:
>
>> livibetter <livibetter@gmail.com> wrote:
>>>Here is mine for Python:
>>
>> What the f*** does Python have to do with Perl?
>
>Clueless fuck. I unsubscribed from comp.lang.perl.misc to avoid the
>retards like you and now you come in via the backdoor. If you have a
>problem with Xah report him with Google Groups and with his hosting
>provider 1&1 like I do. Dreamhost kicked him out that way.

I have solved my problems with Xah years ago, that's what killfiles are
for. And I have no idea why you are bringing up Xah in your current
rant.

It was livibetter who without any motivation or reasoning posted Python
code in CLPM. If at least he had asked something like "How can I write
something similar in Perl?" or _ANYTHING_ that would have made this even
remotely meaningful for CLPM, then ok.
But he didn't. He just dumped 7 lines of Python code to CLPM and his
only comment was "Here is mine for Python". Yeah, great comment. Why
would anyone in CLPM possibly care about those 7 lines of Phython code?

jue

jue
```
 0

```On Sun, 26 Sep 2010 23:16:24 +0100, Jürgen Exner <jurgenex@hotmail.com>
wrote:

> I have solved my problems with Xah years ago, that's what killfiles are
> for. And I have no idea why you are bringing up Xah in your current
> rant.
>
> It was livibetter who without any motivation or reasoning posted Python
> code in CLPM. If at least he had asked something like "How can I write
> something similar in Perl?" or _ANYTHING_ that would have made this even
> remotely meaningful for CLPM, then ok.
> But he didn't. He just dumped 7 lines of Python code to CLPM and his
> only comment was "Here is mine for Python". Yeah, great comment. Why
> would anyone in CLPM possibly care about those 7 lines of Phython code?

Check the Newsgroups line: this is a standard Xah "cross-post to
everywhere in sight" troll.  Hence (a) bringing up Xah, since he
originated this thread, and (b) livibetter not thinking to trim the
crossposts.  Which you didn't either, I note.

The only downside to killfiles is that you have to pay attention or
you sometimes get bitten by this stuff.

--
Rhodri James *-* Wildebeest Herder to the Masses
```
 0

```Xah Lee <xahlee@gmail.com> wrote:

> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by a number. I
> need to collect together the contents of all sublists sharing the same
> label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> [...]
>
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.

In Haskell the solution looks like this:

import qualified Data.Map as M
import qualified Data.Set as S
import Data.Map (Map)
import Data.Set (Set)

collect :: (Ord a, Ord k) => [Map k (Set a)] -> Map k (Set a)
collect = M.unionsWith S.union

Greets,
Ertugrul

--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

```
 0

```Ertugrul S=C3=B6ylemez <es@ertes.de> wrote:

> In Haskell the solution looks like this:
>
> [...]

And before anyone starts to rant, I didn't pay attention to where I'm
X-posting this stuff.  Sorry for that.  But on the other hand you could
say that I'm giving the Perl people (apparently the only people feeling
the urge to rant anyway) the chance to come up with a more elegant
solution. =3D)

Greets,
Ertugrul

--=20
nightmare =3D unsafePerformIO (getWrongWife >>=3D sex)
http://ertes.de/

```
 0

```Quoth Ertugrul =?UTF-8?B?U8O2eWxlbWV6?= <es@ertes.de>:
> Ertugrul Söylemez <es@ertes.de> wrote:
>
> > In Haskell the solution looks like this:
>
> And before anyone starts to rant, I didn't pay attention to where I'm
> X-posting this stuff.  Sorry for that.  But on the other hand you could
> say that I'm giving the Perl people (apparently the only people feeling
> the urge to rant anyway)

I don't know about the other groups, but we get Xah Lee threads fairly
regularly. After a while they start to get on your nerves...

> the chance to come up with a more elegant
> solution. =)

Hmmm. Not likely :)

Ben

```
 0

```On Sep 26, 12:05=A0am, Xah Lee <xah...@gmail.com> wrote:

I am hijacking the following post and driving it to Cuba (the Monthy
Python fans will know what I refer to).  I want to create a `reduce'-
like function that can handle similar problems.

Xah said:
> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> stuffed deleted.

Here is my Common Lisp (and I only care about Common Lisp answers)
attempt to create a `reduce'-like function to handle this kind of a
problem (you will see that I am still struggling with the code and the
documentation).

(defun reduce-tagged (function sequence &key
(key-tag #'first)
(key-datum #'rest))
"Use a binary operation, `function' to combine a sequence of tagged
elements.  like-tagged elements are `reduce'd according to `function'
and returned in a list ...

`sequence' is a sequence of tagged elements.  reduce-m will reduce
like-tagged-elements.

If `key-tag' is supplied it is used to extract the element tag.  If
`key-tag' is not supplied, the function `first' is used.

If `key-datum' is supplied, it is used to extract the element datum.
If `key-datum' is not supplied, the function `rest' is used.

"
(let ((hash (make-hash-table)))
(dolist (datum sequence)
(let ((tag (funcall key-tag datum))
(values (funcall key-datum datum)))
(multiple-value-bind (it present)
(gethash tag hash)
(if present
(setf (gethash tag hash)
(apply function (gethash tag hash) values))
(setf (gethash tag hash) values)))))
(let (result)
(dohash (key value hash)
(push (list key value) result))
result)))

Comments, improvements?  I am looking for a general purpose function
like reduce that I
can apply in various situations.

Thanks,

Mirko
```
 0

```On Sep 27, 11:18=A0am, Mirko <mirko.vuko...@gmail.com> wrote:
> On Sep 26, 12:05=A0am, Xah Lee <xah...@gmail.com> wrote:
>
> I am hijacking the following post and driving it to Cuba (the Monthy
> Python fans will know what I refer to). =A0I want to create a `reduce'-
> like function that can handle similar problems.
>
> Xah said:
>
>
>
> > here's a interesting toy list processing problem.
>
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
>
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > r) (5 s t))
>
> > where the first element of each sublist is the label, I need to
> > produce:
>
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > stuffed deleted.
>
> Here is my Common Lisp (and I only care about Common Lisp answers)
> attempt to create a `reduce'-like function to handle this kind of a
> problem (you will see that I am still struggling with the code and the
> documentation).
>
> (defun reduce-tagged (function sequence &key
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0(key-tag #'first)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0(key-datum #'rest))
> =A0 "Use a binary operation, `function' to combine a sequence of tagged
> elements. =A0like-tagged elements are `reduce'd according to `function'
> and returned in a list ...
>
> `sequence' is a sequence of tagged elements. =A0reduce-m will reduce
> like-tagged-elements.
>
> If `key-tag' is supplied it is used to extract the element tag. =A0If
> `key-tag' is not supplied, the function `first' is used.
>
> If `key-datum' is supplied, it is used to extract the element datum.
> If `key-datum' is not supplied, the function `rest' is used.
>
> "
> =A0 (let ((hash (make-hash-table)))
> =A0 =A0 (dolist (datum sequence)
> =A0 =A0 =A0 (let ((tag (funcall key-tag datum))
> =A0 =A0 =A0 =A0 =A0 =A0 (values (funcall key-datum datum)))
> =A0 =A0 =A0 =A0 (multiple-value-bind (it present)
> =A0 =A0 =A0 =A0 =A0 =A0 (gethash tag hash)
> =A0 =A0 =A0 =A0 =A0 (if present
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 (setf (gethash tag hash)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 (apply function (gethash tag hash=
) values))
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 (setf (gethash tag hash) values)))))
> =A0 =A0 (let (result)
> =A0 =A0 =A0 (dohash (key value hash)
> =A0 =A0 =A0 =A0 (push (list key value) result))
> =A0 =A0 =A0 result)))
>
> Comments, improvements? =A0I am looking for a general purpose function
> like reduce that I
> can apply in various situations.
>
> Thanks,
>
> Mirko

Correction: the previous code used a non-portable clisp macro
`dohash' (looks nice, doesn't it?)

Here is the version with maphash:

(defun reduce-tagged (function sequence &key
(key-tag #'first)
(key-datum #'rest))
"Use a binary operation, `function' to combine a sequence of tagged
elements.  like-tagged elements are `reduce'd according to `function'

`sequence' is a sequence of tagged elements.  reduce-m will reduce
like-tagged-elements.

If `key-tag' is supplied it is used to extract the element tag.  If
`key-tag' is not supplied, the function `first' is used.

If `key-datum' is supplied, it is used to extract the element datum.
If `key-datum' is not supplied, the function `rest' is used.

"
(let ((hash (make-hash-table)))
(dolist (datum sequence)
(let ((tag (funcall key-tag datum))
(values (funcall key-datum datum)))
(multiple-value-bind (it present)
(gethash tag hash)
(declare (ignore it))
(if present
(setf (gethash tag hash)
(apply function (gethash tag hash) values))
(setf (gethash tag hash) values)))))
(let (result)
(maphash #'(lambda(key value)
(push (list key value) result))
hash)
result)))

Mirko
```
 0

```On Sep 27, 11:40=A0am, Mirko <mirko.vuko...@gmail.com> wrote:
> On Sep 27, 11:18=A0am, Mirko <mirko.vuko...@gmail.com> wrote:
>
>
>
> > On Sep 26, 12:05=A0am, Xah Lee <xah...@gmail.com> wrote:
>
> > I am hijacking the following post and driving it to Cuba (the Monthy
> > Python fans will know what I refer to). =A0I want to create a `reduce'-
> > like function that can handle similar problems.
>
> > Xah said:
>
> > > here's a interesting toy list processing problem.
>
> > > I have a list of lists, where each sublist is labelled by
> > > a number. I need to collect together the contents of all sublists
> > > sharing
> > > the same label. So if I have the list
>
> > > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > > r) (5 s t))
>
> > > where the first element of each sublist is the label, I need to
> > > produce:
>
> > > output:
> > > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > > stuffed deleted.
>
> > Here is my Common Lisp (and I only care about Common Lisp answers)
> > attempt to create a `reduce'-like function to handle this kind of a
> > problem (you will see that I am still struggling with the code and the
> > documentation).
>
> ... faulty code deleted

Aaand one more fix (apply -> funcall)  (This version at least produces
a close
facsimile of the desired output)

(defun reduce-tagged (function sequence &key
(key-tag #'first)
(key-datum #'rest))
"Use a binary operation, `function' to combine a sequence of tagged
elements.  like-tagged elements are `reduce'd according to `function'

`sequence' is a sequence of tagged elements.  reduce-m will reduce
like-tagged-elements.

If `key-tag' is supplied it is used to extract the element tag.  If
`key-tag' is not supplied, the function `first' is used.

If `key-datum' is supplied, it is used to extract the element datum.
If `key-datum' is not supplied, the function `rest' is used.

"
(let ((hash (make-hash-table)))
(dolist (datum sequence)
(let ((tag (funcall key-tag datum))
(values (funcall key-datum datum)))
(multiple-value-bind (it present)
(gethash tag hash)
(declare (ignore it))
(if present
(setf (gethash tag hash)
(funcall function (gethash tag hash) values))
(setf (gethash tag hash) values)))))
(let (result)
(maphash #'(lambda(key value)
(push (list key value) result))
hash)
result)))
```
 0

```On Sep 26, 12:05=A0am, Xah Lee <xah...@gmail.com> wrote:
> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

Here is a solution in Perl -- the verbose version. Please see my note
below.

SCRIPT:
use strict;
use warnings;
my %lists;

while (<DATA>)
{
chomp;
my (\$k, @v) =3D split(/ /, \$_);
push(@{\$lists{\$k}}, @v);
}

foreach my \$k (sort keys %lists)
{
print "\$k - @{\$lists{\$k}}\n";
}

exit(0);

__DATA__
0 a b
1 c d
2 e f
3 g h
1 i j
2 k l
4 m n
2 o p
4 q r
5 s t

OUTPUT:
>perl lists.plx
0 - a b
1 - c d i j
2 - e f k l o p
3 - g h
4 - m n q r
5 - s t

NOTE:
I assume that you want an idiomatic solution for the language. I have
therefore converted your data into a typical record oriented
structure. Perlistas don't use parenthesis. If you want a Lispy
solution, use Lisp. Further, Perl was made for exactly this kind of
problem, which is simple data munging, taking some input, transforming
it, and printing it out -- Practical Extraction and Reporting
Language. I know that some Lispers (R.G., are you reading?) will
object to a formulation like this: @{\$lists{\$k}}, but all this says
(in Perl) is to spit out the value contained in the hash element
\$lists{\$k} as an array, and is good idiomatic Perl, even if some
Lispers aren't quite up to the task of understanding it.

CC.
```
 0

```On Mon, 27 Sep 2010 08:18:22 -0700, Mirko wrote:

> Here is my Common Lisp (and I only care about Common Lisp answers)

Good for you. So why are you spamming other newsgroups with your CL
solution? Not once, but three times.

Replies to /dev/null.

--
Steven
```
 0

```On 2010-09-26, Xah Lee <xahlee@gmail.com> wrote:
> On Sep 25, 11:17??pm, Paul Rubin <no.em...@nospam.invalid> wrote:
>> Python solution follows (earlier one with an error cancelled). ??All
>> crossposting removed since crossposting is a standard trolling tactic.

You're wrong.  Crossposting is indeed a standard trolling tactic.

This does not prove that all crossposters are trolls, nor does it assert
that all crossposters are trolls, but it is absolutely factually correct
that it's a standard trolling tactic.

-s
--
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
```
 0

```On 2010-09-26, J?rgen Exner <jurgenex@hotmail.com> wrote:
> It was livibetter who without any motivation or reasoning posted Python
> code in CLPM.

Not exactly; he posted it in a crossposted thread, which happened to include
CLPM and other groups, including comp.lang.python.

It is quite possible that he didn't know about the crossposting.  However,
while I would agree that this would constitute a form of ignorance, I'd think
that, especially with how well some newsreading interfaces hide that detail,
I don't think it's really worth getting angry over.

-s
--
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
```
 0

```Seebs <usenet-nospam@seebs.net> writes:

> On 2010-09-26, Xah Lee <xahlee@gmail.com> wrote:
>> On Sep 25, 11:17??pm, Paul Rubin <no.em...@nospam.invalid> wrote:
>>> Python solution follows (earlier one with an error cancelled). ??All
>>> crossposting removed since crossposting is a standard trolling tactic.
>
>
> You're wrong.

FYI: Xah Lee is well known for his abuse of cross posting. Be happy that
Google Groups limits the number of groups to crosspost to five.

Related: his spamming behaviour has already resulted in Xah Lee
having to look for another hosting provider [1]. Currently 1and1 provides
him shelter, most likely carefully selected by Xah (as Google Groups)
since 1and1 is not known for their spam fighting reputation nor clue.

respect from it, but maybe you end up being honored [2] on his
collection of drivel [3].

In short:

= don't reply to Xah Lee: at best it's a waste of time
= if his post is abusive (crossposting to 5 groups just because you can
is) report it with /and/ his hosting provider (since most of his
posts are copy paste jobs of articles on his site just to drive
traffic) and Google Groups (his Usenet provider of choice since they
hardly do a thing about spam).

[1] http://www.mail-archive.com/python-list@python.org/msg91631.html
[3] What's sad is that some of its stuff is actually good/not bad.
But tainted: Xah Lee is a spammer and a Usenet abuser.

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0

```Seebs <usenet-nospam@seebs.net> writes:

> On 2010-09-26, J?rgen Exner <jurgenex@hotmail.com> wrote:
>> It was livibetter who without any motivation or reasoning posted Python
>> code in CLPM.
>
> Not exactly; he posted it in a crossposted thread, which happened to include
> CLPM and other groups, including comp.lang.python.
>
> It is quite possible that he didn't know about the crossposting.

Oh, he does. It has been Xah's game for years.

> while I would agree that this would constitute a form of ignorance, I'd think
> that, especially with how well some newsreading interfaces hide that detail,
> I don't think it's really worth getting angry over.

You think wrong. And Jurgen should have known better than to reply several
times (but like too many people in cplm he posts for posting's sake, the
main reason why I don't follow that group anymore).

Xah has been doing this for many years and most of his posts are just
made to drive traffic to his site (hence they are copy paste of articles
on his site + link(s) to his site). It's Usenet abuse, on purpose.

The reason it pisses off people is that nearly weekly it causes a lot of
noise in newsgroups that are really better off without the noise
(IMNSHO).

See my other post on how to deal with this spammer. If you've missed it:
report him for spamming, since that's what he does. It already made him
have to move hosting providers once. While it's not going to stop him,
it will cost him money. See:

While I am named in that article be assured that I was not the only one
contacting dreamhost (+10 for doing this, btw). Quite some people
contacted me via email that they also talked with Dreamhost. Just keep
reporting this spammer, and maybe 1and1 will kick it out.

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0

```On 2010-09-28, John Bokma <john@castleamber.com> wrote:
> Seebs <usenet-nospam@seebs.net> writes:
>> On 2010-09-26, J?rgen Exner <jurgenex@hotmail.com> wrote:
>>> It was livibetter who without any motivation or reasoning posted Python
>>> code in CLPM.

>> Not exactly; he posted it in a crossposted thread, which happened to include
>> CLPM and other groups, including comp.lang.python.

>> It is quite possible that he didn't know about the crossposting.

> Oh, he does. It has been Xah's game for years.

But did "livibetter" know about it?  I wasn't defending Xah, who is indeed
at the very least clueless and disruptive.  But I was sort of defending
the poster who was accused of posting Python code in CLPM, because that
poster may not have understood the game.

-s
--
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
```
 0

```Seebs <usenet-nospam@seebs.net> writes:

fup set to poster

> On 2010-09-28, John Bokma <john@castleamber.com> wrote:
>> Seebs <usenet-nospam@seebs.net> writes:
>>> On 2010-09-26, J?rgen Exner <jurgenex@hotmail.com> wrote:
>>>> It was livibetter who without any motivation or reasoning posted Python
>>>> code in CLPM.
>
>>> Not exactly; he posted it in a crossposted thread, which happened to include
>>> CLPM and other groups, including comp.lang.python.
>
>>> It is quite possible that he didn't know about the crossposting.
>
>> Oh, he does. It has been Xah's game for years.
>
> But did "livibetter" know about it?  I wasn't defending Xah, who is indeed
> at the very least clueless and disruptive.

Heh, he's not clueless, the problem is that he knows exactly what he's
doing. And like most spammers, very hard to get rid off.

> But I was sort of defending
> the poster who was accused of posting Python code in CLPM, because that
> poster may not have understood the game.

Ah, clear. Well, the problem is somewhat also in CLPM where people
somehow have to reply to messages like this :-(. And I am sure Xah
laughes his ass off each time it happens.

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0

```On Sep 27, 9:34=C2=A0pm, John Bokma <j...@castleamber.com> wrote:
> Seebs <usenet-nos...@seebs.net> writes:
>
> fup set to poster
>
> > On 2010-09-28, John Bokma <j...@castleamber.com> wrote:
> >> Seebs <usenet-nos...@seebs.net> writes:
> >>> On 2010-09-26, J?rgen Exner <jurge...@hotmail.com> wrote:
> >>>> It was livibetter who without any motivation or reasoning posted Pyt=
hon
> >>>> code in CLPM.
>
> >>> Not exactly; he posted it in a crossposted thread, which happened to =
include
> >>> CLPM and other groups, including comp.lang.python.
>
> >>> It is quite possible that he didn't know about the crossposting.
>
> >> Oh, he does. It has been Xah's game for years.
>
> > But did "livibetter" know about it? =C2=A0I wasn't defending Xah, who i=
s indeed
> > at the very least clueless and disruptive.
>
> Heh, he's not clueless, the problem is that he knows exactly what he's
> doing. And like most spammers, very hard to get rid off.
>
> > But I was sort of defending
> > the poster who was accused of posting Python code in CLPM, because that
> > poster may not have understood the game.
>
> Ah, clear. Well, the problem is somewhat also in CLPM where people
> somehow have to reply to messages like this :-(. And I am sure Xah
> laughes his ass off each time it happens.

Hi John Bokma,

can you stop this?

doesn't seems fruitful to keep on this.

if you don't like my posts, ignore them? i don't post in
comp.lang.python or comp.lang.perl.misc that often... maybe have done
so 5 times this year.

http://johnbokma.com/mexit/2010/08/15/
and there are really a lot beautiful photos.

this isn't bribery or something like that. I've been annoyed by you,
of course, but it's not fruitful to keep going on this.

Best,

Xah =E2=88=91 xahlee.org =E2=98=84
```
 0

```Xah Lee <xahlee@gmail.com> writes:

> can you stop this?

Can you stop crossposting? And if there is really, really a need to
crosspost, can you please set the follow-up to?

> doesn't seems fruitful to keep on this.
>
> if you don't like my posts, ignore them? i don't post in
> comp.lang.python or comp.lang.perl.misc that often... maybe have done
> so 5 times this year.

Which is enough to disrupt those groups for days.

> http://johnbokma.com/mexit/2010/08/15/
> and there are really a lot beautiful photos.

Thanks Xah. Like I wrote, your site /does/ have good information, it's
so sad that you somehow think it's necessary to spam Usenet to get
visitors. Or maybe you've another reason, don't know. But it /is/ Usenet
abuse.

> this isn't bribery or something like that. I've been annoyed by you,
> of course, but it's not fruitful to keep going on this.

Well, you annoy me, I annoy you. It's in your hands to make it stop.

1) remove all the excessive swearing from your site. If you have a
point, you don't need it. Your argument(s) without the swearing
should speak for themselves

2) Stop abusing Usenet. Instead focus on writing more good stuff on

1) & 2) will keep me from linking to your site, ever. And I am sure I am
not alone in this.

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0

```John Bokma <john@castleamber.com> writes:
> Xah Lee <xahlee@gmail.com> writes: ...
> Can you stop crossposting?

John, can you ALSO stop crossposting?
```
 0
Reply no.email6 (1524) 9/28/2010 7:11:39 PM

```Paul Rubin <no.email@nospam.invalid> writes:

> John Bokma <john@castleamber.com> writes:
>> Xah Lee <xahlee@gmail.com> writes: ...
>> Can you stop crossposting?
>
> John, can you ALSO stop crossposting?

Since the issue is on-topic in all groups: no. I did set a follow-up
header, which you ignored and on top of that redirected the thing to
comp.lang.python. So:

Paul, can you ALSO stop acting like a complete ass?

--
John Bokma                                                               j3b

Freelance Perl & Python Development: http://castleamber.com/
```
 0
Reply john167 (400) 9/28/2010 8:12:56 PM

```On Sep 26, 9:24=A0am, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
> Xah Lee <xah...@gmail.com> writes:
> > here's a interesting toy list processing problem.
>
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
>
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > r) (5 s t))
>
> > where the first element of each sublist is the label, I need to
> > produce:
>
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > a Mathematica solution is here:
> >http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> > R5RS Scheme lisp solution:
> >http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_...
> > by Sourav Mukherjee
>
> > also, a Common Lisp solution can be found here:
>
> It's too complex. Just write:
>
> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 (2 o p) (4 q r) (5 s t))))
>
> =A0 (mapcar (lambda (class) (reduce (function append) class :key (functio=
n rest)))
> =A0 =A0 =A0 =A0 =A0 =A0(com.informatimago.common-lisp.list:equivalence-cl=
asses list :key (function first)))
>
> =A0 =A0)
>
> --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> --
> __Pascal Bourguignon__ =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0http://www.=
informatimago.com/

Ruby:

[[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
[5, 's', 't']].
group_by{|x| x.first}.values.map{|x| x.map{|y| y[1..-1]}.flatten}

=3D=3D>[["s", "t"], ["a", "b"], ["c", "d", "i", "j"],
["e", "f", "k", "l", "o", "p"],
["g", "h"], ["m", "n", "q", "r"]]
```
 0

```On 29 set, 11:04, w_a_x_man <w_a_x_...@yahoo.com> wrote:
> On Sep 26, 9:24=A0am, p...@informatimago.com (Pascal J. Bourguignon)
> wrote:
>
>
>
> > Xah Lee <xah...@gmail.com> writes:
> > > here's a interesting toy list processing problem.
>
> > > I have a list of lists, where each sublist is labelled by
> > > a number. I need to collect together the contents of all sublists
> > > sharing
> > > the same label. So if I have the list
>
> > > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > > r) (5 s t))
>
> > > where the first element of each sublist is the label, I need to
> > > produce:
>
> > > output:
> > > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > > a Mathematica solution is here:
> > >http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> > > R5RS Scheme lisp solution:
> > >http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_.=
...
> > > by Sourav Mukherjee
>
> > > also, a Common Lisp solution can be found here:
...
>
> > It's too complex. Just write:
>
> > (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 (2 o p) (4 q r) (5 s t))))
>
> > =A0 (mapcar (lambda (class) (reduce (function append) class :key (funct=
ion rest)))
> > =A0 =A0 =A0 =A0 =A0 =A0(com.informatimago.common-lisp.list:equivalence-=
classes list :key (function first)))
>
> > =A0 =A0)
>
> > --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> > --
> > __Pascal Bourguignon__ =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0http://ww=
w.informatimago.com/
>
> Ruby:
>
> [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
> 'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
> [5, 's', 't']].
> group_by{|x| x.first}.values.map{|x| x.map{|y| y[1..-1]}.flatten}
>
> =A0 =A0 =3D=3D>[["s", "t"], ["a", "b"], ["c", "d", "i", "j"],
> =A0["e", "f", "k", "l", "o", "p"],
> =A0["g", "h"], ["m", "n", "q", "r"]]

cool, it comes with order all fucked up.  This is something I was
criticized for before, though not all that important to most
functional processing.  Not the case here, though.

here's a scheme version that is hopefully better than the given one:

(define (dig in)

(if (null? in) '()

(let* ((n         (first-of-first in))

(all-n     (filter in (lambda (x)      (eq? n (first x)))))

(all-but-n (filter in (lambda (x) (not (eq? n (first
x)))))))

(pair

(fold all-n
(lambda (i o) (pair (second i) (pair (third i) o))))

(dig all-but-n)))))

; given these aliases to lisp n00bs

(define pair cons)

(define first car)

(define rest cdr)

(define first-of-first caar)

; and these well-known functions
(non-tail-recursive for benefit of n00bs)
(define (fold ls f) ; AKA reduce

(if (null? ls) '()

(f (first ls) (fold (rest ls) f))))

(define (filter ls f)

(fold ls (lambda (i o) (if (f i) (pair i o) o))))

; testing
(let ((in '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
(2 o p) (4 q r) (5 s t))))
(display (dig in))
(newline))

```
 0

```On 30 set, 09:35, namekuseijin <namekusei...@gmail.com> wrote:
> On 29 set, 11:04, w_a_x_man <w_a_x_...@yahoo.com> wrote:
>
>
>
> > On Sep 26, 9:24=A0am, p...@informatimago.com (Pascal J. Bourguignon)
> > wrote:
>
> > > Xah Lee <xah...@gmail.com> writes:
> > > > here's a interesting toy list processing problem.
>
> > > > I have a list of lists, where each sublist is labelled by
> > > > a number. I need to collect together the contents of all sublists
> > > > sharing
> > > > the same label. So if I have the list
>
> > > > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4=
q
> > > > r) (5 s t))
>
> > > > where the first element of each sublist is the label, I need to
> > > > produce:
>
> > > > output:
> > > > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > > > a Mathematica solution is here:
> > > >http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> > > > R5RS Scheme lisp solution:
> > > >http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work=
_...
> > > > by Sourav Mukherjee
>
> > > > also, a Common Lisp solution can be found here:
e...
>
> > > It's too complex. Just write:
>
> > > (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
> > > =A0 =A0 =A0 =A0 =A0 =A0 =A0 (2 o p) (4 q r) (5 s t))))
>
> > > =A0 (mapcar (lambda (class) (reduce (function append) class :key (fun=
ction rest)))
> > > =A0 =A0 =A0 =A0 =A0 =A0(com.informatimago.common-lisp.list:equivalenc=
e-classes list :key (function first)))
>
> > > =A0 =A0)
>
> > > --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> > > --
> > > __Pascal Bourguignon__ =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0http://=
www.informatimago.com/
>
> > Ruby:
>
> > [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
> > 'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
> > [5, 's', 't']].
> > group_by{|x| x.first}.values.map{|x| x.map{|y| y[1..-1]}.flatten}
>
> > =A0 =A0 =3D=3D>[["s", "t"], ["a", "b"], ["c", "d", "i", "j"],
> > =A0["e", "f", "k", "l", "o", "p"],
> > =A0["g", "h"], ["m", "n", "q", "r"]]
>
> cool, it comes with order all fucked up. =A0This is something I was
> criticized for before, though not all that important to most
> functional processing. =A0Not the case here, though.
>
> here's a scheme version that is hopefully better than the given one:

(define (dig in)
=A0 (if (null? in) '()
=A0 =A0 (let* ((n =A0 =A0 =A0 =A0 (first-of-first in))
=A0 =A0 =A0 =A0 =A0 =A0(all-n =A0 =A0 (filter in (lambda (x) =A0 =A0 =A0(eq=
? n (first x)))))
=A0 =A0 =A0 =A0 =A0 =A0(all-but-n (filter in (lambda (x) (not (eq? n (first
x)))))))
=A0 =A0 =A0 =A0(pair
=A0 =A0 =A0 =A0 =A0 (fold all-n
=A0 =A0 =A0 =A0 =A0 =A0 =A0(lambda (i o) (pair (second i) (pair (third i) o=
))))
=A0 =A0 =A0 =A0 =A0 (dig all-but-n)))))

; given these aliases to lisp n00bs
(define pair cons)
(define first car)
(define rest cdr)
(define first-of-first caar)

; and these well-known functions=A0(non-tail-recursive for benefit of
n00bs)
(define (fold ls f) ; AKA reduce
=A0 (if (null? ls) '()
=A0 =A0 =A0 (f (first ls) (fold (rest ls) f))))
(define (filter ls f)
=A0 (fold ls (lambda (i o) (if (f i) (pair i o) o))))

; testing
(let ((in '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
=A0 =A0 =A0 =A0 =A0 =A0 (2 o p) (4 q r) (5 s t))))
=A0 (display (dig in))
=A0 (newline))

;frakkin text editor...
```
 0

```Hi!

Am 27.09.2010 02:56, schrieb Ben Morrow:
>> Ertugrul Söylemez<es@ertes.de>  wrote:
>>
>>> In Haskell the solution looks like this:  [...]
>
> Hmmm. Not likely :)

It looks like Perl is beaten by better libraries
instead of higher elegance and orthogonality.

The latter isn't a problem: Perl mongers have no problem with
that other people think perl is ugly and dirty.
(Maybe simply because it is true.)

But this was an attack to theirs proudness about the all-embracing  CPAN.

(So at least i start missing
Set::Bag::Value -or- Set::Scalar::MultiValue.)

This posting is cross-posted to c.l.f only, because even some of the
stuff in the appended code looks familiar at first, it holds
things in it which can cause heart attacks to this guys.
So be warned.

One the other side, it is time that functional programmer came in
contact with the real world, instead always be protected by gloves

xp&fup.

just kidding,
josef

DISCLAIMER@c.l.f: Looking at the appended source on your own risk!

O /
---X----------------------------------------------------------
O \                                dedicated_to_a_spammer.pl

#! /usr/bin/env perl
use strict; use warnings;
use Data::Dump 'dump';

my @inp=([0,'a','b'],[1,'c','d'],[2,'e','f'],[3,'g','h'],
[1,'i','j'],[2,'k','l'],[4,'m','n'],[2,'o','p'],
[4,'q','r'],[5,'s','t']);

#helper functions:
#sub distributefirst_as (&@) { ((my \$f),\$a)=splice @_,0,2; map {
\$f->(\$a,\$b=\$_) } @_ }
#sub wo_dup { my %e; grep { ! \$e{\$_}++ } @_ }
# -----------------------------------------------------
print "\ntie variant (first occurence order):\n";
use Tie::Hash::MultiValue;
use Array::Unique;
sub distributefirst { my \$t=shift; map { \$t => \$_ } @_ }
tie my @keys, 'Array::Unique';
tie my %h, 'Tie::Hash::MultiValue';
%h=map { distributefirst @\$_ } @inp;
@keys=map { \$_->[0] } @inp; # or: List::MoreUtils::each_arrayref(@inp)->()
dump @h{@keys};
# -----------------------------------------------------
print "\nreduce variant (first occurence order):\n";
use List::Util qw'reduce first';
dump @{+reduce { my @t=@\$b; push @{\$a->{+shift @t}}, @t; \$a } {},@inp}
{@{+reduce { (first {\$_ eq \$b->[0]} @\$a) ? \$a : [@\$a,\$b->[0]] }
[],@inp}};
# -----------------------------------------------------
print "\narray based reduce variant (key must be a number):\n";
use List::Util 'reduce';
dump reduce { push @{\$a->[\$b->[0]]}, @{\$b}[1..\$#\$b]; \$a } [],@inp;
#or: dump reduce { push @{\$a->[shift \$b]}, @\$b; \$a } [],clone @inp;
# ------------------------------------------------------
print "\nperlish array variant (key must be a number):\n";
my @v;
push @{\$v[\$_->[0]]}, @{\$_}[1..\$#\$_] for @inp;
dump @v;
# ------------------------------------------------------
print "\npresort variant (alphabetically orderd):\n";
sub butfirst { @_[1..\$#_] }; sub deref { @{\$_[0]} };
sub clone { map {[@\$_]} @_ }
my @sorted=sort { \$a->[0] cmp \$b->[0] } clone @inp;
dump map { [ butfirst @\$_ ] } deref # @{\$_}[1..\$#\$_]
reduce { \$a->[\$#\$a]->[0] ne \$b->[0] ? [@\$a,\$b] :
(push @{\$a->[\$#\$a]},butfirst @\$b)&&\$a }
[\$sorted[0]],butfirst @sorted;
# ------------------------------------------------------
print "\npresort variant2 (alphabetically orderd):\n";
@sorted=sort { \$a->[0] cmp \$b->[0] } @inp;
dump grep { shift @\$_;1 } map { @\$_ } #=deref
reduce { my (\$b0,@br)=@\$b;\$a->[\$#\$a]->[0] ne \$b0 ? [@\$a,[@\$b]] :
[@\$a[0..\$#\$a-1],[@{\$a->[\$#\$a]},@br]] }
[[@{\$sorted[0]}]],@sorted[1..\$#sorted];
#dump @inp;
# ------------------------------------------------------
print "\nTie::IxHash variant (first occurence order):\n";
use Tie::IxHash;
tie my %ixh, 'Tie::IxHash';
push @{\$ixh{\$_->[0]}}, @{\$_}[1..\$#\$_] for @inp;
#or: push @{\$h{+shift @\$_}},@\$_ for clone @inp;
dump values @v;
# ------------------------------------------------------
print "\nTie::IxHash variant2 (first occurence order):\n";
use Tie::IxHash;
tie my %ix2, 'Tie::IxHash';
%ix2=map { my (\$k,@r)=@\$_; \$k => [@{\$ix2{\$k}||[]},@r]} @inp;
dump values @v;
# ------------------------------------------------------
print "\nData::Pairs variant (first occurence order):\n";
use Data::Pairs;
sub makepairs { my \$t=shift; map { { \$t => \$_ } } @_ }
sub wo_dup { my %e; grep { ! \$e{\$_}++ } @_ }
my \$dp=Data::Pairs->new([map { makepairs @\$_ } @inp]);
dump map [\$dp->get_values(\$_)], wo_dup \$dp->get_keys;
# ------------------------------------------------------
#use DBI;
#my \$dbh = DBI->connect('DBI:RAM:','','',{RaiseError=>1});
#\$dbh->func({
#   table_name  => 'inp',
#   col_names   => 'id,value',
#   data_type   => 'ARRAY',
#   data_source => [map { distributefirst @\$_ } @inp]  # nf
#}, 'import' );
#dump \$dbh->selectcol_arrayref('SELECT value FROM inp GROUP BY id');
```
 0

```On Sat, 25 Sep 2010 21:05:13 -0700 (PDT), Xah Lee <xahlee@gmail.com> wrote:

>here's a interesting toy list processing problem.
>
>I have a list of lists, where each sublist is labelled by
>a number. I need to collect together the contents of all sublists
>sharing
>the same label. So if I have the list
>
>((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
>r) (5 s t))
>
>where the first element of each sublist is the label, I need to
>produce:
>
>output:
>((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
[snip]

>anyone care to give a solution in Python, Perl, javascript, or other
>lang? am guessing the scheme solution can be much improved... perhaps
>using some lib but that seems to show scheme is pretty weak if the lib
>is non-standard.
>

Crossposting to Lisp, Python and Perl because the weird list of lists looks
like Lisp or something else, and you mention other languages so I'm throwing
this out for Perl.

It appears this string you have there is actually list syntax in another language.
If it is, its the job of the language to parse the data out. Why then do you
want to put it into another language form? At runtime, once the data is in variables,
dictated by the syntax, you can do whatever data manipulation you want
(combining arrays, etc..).

So, in the spirit of a preprocessor, given that the text is balanced, with proper closure,
ie:   ( (data) (data) )    is ok.
( data (data) )      is not ok.

the below does simple text manipulation, joining like labeled sublists, without going into
the runtime guts of internalizing the data itself. Internally, this is too simple.

-sln
-----------------
Alternate input:
(
(
(0 a b) (1 c d) (2 e f )
)
(3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r) (5 s t)
)
------------------
use strict;
use warnings;

my \$input = <<EOI;
((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r)
(5 s t))
EOI
my \$output = \$input;

my \$regxout = qr/
( (?: \( \s* [^()]+ \s* \) (\s*) )+ )
/x;

\$output =~
s{ \$regxout }
{
my ( \$list, \$format ) = ( \$1, \$2 );
my ( %hseen,
@order,
\$replace
);
while (\$list =~  /\(\s* (\S+) \s* (.+?) \s*\)/xsg) {
if ( exists \$hseen{\$1} ) {
\$hseen{\$1} .= " \$2";
next;
}
push @order, \$1;
\$hseen{\$1} = \$2;
}
for my \$id (@order) {
\$replace .= "(\$hseen{\$id}) ";
}
\$replace =~ s/ \$//;
\$replace . \$format
}xeg;

print "Input  -\n\$input\n";
print "Output -\n\$output";

__END__

Input  -
((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r)
(5 s t))

Output -
((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

```
 0

```sln@netherlands.com writes:

> On Sat, 25 Sep 2010 21:05:13 -0700 (PDT), Xah Lee <xahlee@gmail.com> wrote:
>
> >here's a interesting toy list processing problem.
> >
> >I have a list of lists, where each sublist is labelled by
> >a number. I need to collect together the contents of all sublists
> >sharing
> >the same label. So if I have the list
> >
> >((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> >r) (5 s t))
> >
> >where the first element of each sublist is the label, I need to
> >produce:
> >
> >output:
> >((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

I will assume that you need to preserve the order of the sublist
elements.  Or would

((a b) (c d i j) (o p k l e f) (g h) (q r m n) (s t))

also be an acceptable solution?  This is mainly an efficiency issue.

Here are a couple of Common Lisp solutions.  Running time assumes that
the O(x^2) time for multiple appends is minimal.  If the internal order
doesn't matter, then the direction of the append can be reversed with
reduction of the O(x^2) to O(x).

(defun order-keyed-elements (input)
"An array-based solution.  Assumes all keys are non-negative
integers. Works best with dense key sequences. O(n)"
(let* ((max-key (loop for (key . nil) in input maximize key))
(array (make-array (1+ max-key) :initial-element nil)))
(loop for (key . values) in input
do (setf (aref array key) (append (aref array key) values)))
(loop for values across array
unless (null values) collect values)))

(defun order-keyed-elements (input)
"A hash-table-based solution. No restriction on key value. O(n log n)"
(let ((ht (make-hash-table))
(output nil))
(loop for (key . values) in input
do (setf (gethash key ht) (append (gethash key ht nil) values)))
(maphash #'(lambda (k v) (push (cons k v) output)) ht)
(mapcar #'rest (sort output #'< :key #'first))))

(defun order-keyed-elements (input)
"A different hash-table-based solution. No restriction on key
value. O(n^2)"
(let ((ht (make-hash-table))
(keys nil))
(loop for (key . values) in input
do (setf (gethash key ht) (append (gethash key ht nil) values))
(pushnew key keys))
(setq keys (sort keys #'<))
(loop for key in keys collect (gethash key ht))))

(defun order-keyed-elements (input)
"A different hash-table-based solution. No restriction on key
value. O(n log n)"
(let ((ht (make-hash-table))
(keys nil))
(loop for (key . values) in input
do (multiple-value-bind (old-values foundp) (gethash key ht nil)
(if foundp
(setf (gethash key ht) (append old-values values))
(setf (gethash key ht) values
keys (cons key keys)))))
(setq keys (sort keys #'<))
(loop for key in keys collect (gethash key ht))))

--
Thomas A. Russ,  USC/Information Sciences Institute
```
 0
Reply tar (1630) 10/6/2010 7:36:46 PM

```Am 05.10.2010 18:59, schrieb Josef:
> (So at least i start missing
> Set::Bag::Value -or- Set::Scalar::MultiValue.)
>
> This posting is cross-posted to c.l.f only, because even some of the
> stuff in the appended code looks familiar at first, it holds
> things in it which can cause heart attacks to this guys.
> So be warned.  [...]

Because of unknown reason, i remember on Cinderella.
Or more the Ashputtel version of the Grimm brothers.
So here is the best of the story in perl.

<perlcode>
# foreword
use strict; use Data::Dump 'dump'; use List::Util 'reduce';

my @inp=([0,'a','b'],[1,'c','d'],[2,'e','f'],[3,'g','h'],
[1,'i','j'],[2,'k','l'],[4,'m','n'],[2,'o','p'],
[4,'q','r'],[5,'s','t']);

# chapter 1
sub spreadondishtowel  { map { my (\$f,@r)=@\$_; [ \$f => \@r ] } @_ }
# so the lentil coat is better visible.
sub pigeon; sub goiter { reduce { [@\$a,@\$b] } @_ } # concat
sub pigeon    # beside grouping, the pigeons peel the lentils
{ my (\$lentil,@ash)=@_; my \$ok=sub { \$lentil->[0] eq \$_[0][0] };
@ash
? ((goiter \$lentil->[1], map { \$ok->(\$_) ? \$_->[1] : () } @ash),
pigeon grep !\$ok->(\$_), @ash)
: \$lentil->[1]
}
</perlcode>

I don't know the reason of the silence,
but if anybody of the c.l.f people indeed fall sick.
This time the code example is attempt for resuscitation, or
at least to sedate your hearts.   ;-)

xp.

let rising a white dove of peace,
josef
```
 0

```On Wed, 06 Oct 2010 10:52:19 -0700, sln@netherlands.com wrote:

>On Sat, 25 Sep 2010 21:05:13 -0700 (PDT), Xah Lee <xahlee@gmail.com> wrote:
>
>>here's a interesting toy list processing problem.
>>
>>I have a list of lists, where each sublist is labelled by
>>a number. I need to collect together the contents of all sublists
>>sharing
>>the same label. So if I have the list
>>
>>((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
>>r) (5 s t))
>>
>>where the first element of each sublist is the label, I need to
>>produce:
>>
>>output:
>>((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>>
>[snip]
>
>>anyone care to give a solution in Python, Perl, javascript, or other
>>lang? am guessing the scheme solution can be much improved... perhaps
>>using some lib but that seems to show scheme is pretty weak if the lib
>>is non-standard.
>>
>
>Crossposting to Lisp, Python and Perl because the weird list of lists looks
>like Lisp or something else, and you mention other languages so I'm throwing
>this out for Perl.
>
>It appears this string you have there is actually list syntax in another language.
>If it is, its the job of the language to parse the data out. Why then do you
>want to put it into another language form? At runtime, once the data is in variables,
>dictated by the syntax, you can do whatever data manipulation you want
>(combining arrays, etc..).
>
>So, in the spirit of a preprocessor, given that the text is balanced, with proper closure,
>ie:   ( (data) (data) )    is ok.
>      ( data (data) )      is not ok.
>
>the below does simple text manipulation, joining like labeled sublists, without going into
>the runtime guts of internalizing the data itself. Internally, this is too simple.
>

If not preprocessor, then ...
The too simple, order independent, id independent, Perl approach.

-sln
-----------------

use strict;
use warnings;
use Data::Dump 'dump';

my @inp = ([0,'a','b'],[1,'c','d'],[2,'e','f'],[3,'g','h'],
[1,'i','j'],[2,'k','l'],[4,'m','n'],[2,'o','p'],
[4,'q','r'],[5,'s','t']);

my (\$cnt, @outp, %hs) = (0);

for my \$ref (@inp) {
\$hs{ \$\$ref[0] } or \$hs{ \$\$ref[0] } = \$cnt++;
push @{\$outp[ \$hs{ \$\$ref[0] } ] }, @{\$ref}[ 1 .. \$#{\$ref} ];
}

dump @outp;

__END__

(
["a", "b"],
["c", "d", "i", "j"],
["e", "f", "k", "l", "o", "p"],
["g", "h"],
["m", "n", "q", "r"],
["s", "t"],
)

```
 0

```Josef <e9427749@stud4.tuwien.ac.at> wrote:

> I don't know the reason of the silence,
> but if anybody of the c.l.f people indeed fall sick.
> This time the code example is attempt for resuscitation, or
> at least to sedate your hearts.   ;-)

Functional programmers write obfuscated code, too.  But unlike Perl, it
still looks beautiful.

type List a =
forall i r. (i -> a -> (i -> r) -> r) -> i -> (i -> r) -> r

empty :: List a
empty = \fold z k -> k z

cons :: a -> List a -> List a
cons x xs = \fold z k -> fold z x (\y -> xs fold y k)

sumList :: Num a => List a -> a
sumList xs = xs (\x y k -> k (x+y)) 0 id

headList :: List a -> Maybe a
headList xs = xs (\_ x _ -> Just x) Nothing id

printList :: Show a => List a -> IO ()
printList xs = xs (\x y k -> k (x >> print y)) (return ()) id

SCNR. =)

Greets,
Ertugrul

--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

```
 0

```Josef <e9427749@stud4.tuwien.ac.at> wrote:

> I don't know the reason of the silence,
> but if anybody of the c.l.f people indeed fall sick.
> This time the code example is attempt for resuscitation, or
> at least to sedate your hearts.   ;-)

Functional programmers write obfuscated code, too.  But unlike Perl, it
still looks beautiful.

type List a =
forall i r. (i -> a -> (i -> r) -> r) -> i -> (i -> r) -> r

empty :: List a
empty = \fold z k -> k z

cons :: a -> List a -> List a
cons x xs = \fold z k -> fold z x (\y -> xs fold y k)

sumList :: Num a => List a -> a
sumList xs = xs (\x y k -> k (x+y)) 0 id

headList :: List a -> Maybe a
headList xs = xs (\_ x _ -> Just x) Nothing id

printList :: Show a => List a -> IO ()
printList xs = xs (\x y k -> k (x >> print y)) (return ()) id

SCNR. =)

Greets,
Ertugrul

--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

```
 0

```On Thu, 07 Oct 2010 17:44:31 -0700, sln@netherlands.com wrote:

>If not preprocessor, then ...
>The too simple, order independent, id independent, Perl approach.
>
>-sln
>-----------------
>
>use strict;
>use warnings;
>use Data::Dump 'dump';
>
>my @inp = ([0,'a','b'],[1,'c','d'],[2,'e','f'],[3,'g','h'],
>           [1,'i','j'],[2,'k','l'],[4,'m','n'],[2,'o','p'],
>           [4,'q','r'],[5,'s','t']);
>
>my (\$cnt, @outp, %hs) = (0);
>
>for my \$ref (@inp) {
>   \$hs{ \$\$ref[0] } or \$hs{ \$\$ref[0] } = \$cnt++;
^ exists ...
Was left out in a paste

>   push @{\$outp[ \$hs{ \$\$ref[0] } ] }, @{\$ref}[ 1 .. \$#{\$ref} ];
>}
>
>dump @outp;
>
```
 0

```Am 08.10.2010 04:38, schrieb Ertugrul S�ylemez:
> Josef<e9427749@stud4.tuwien.ac.at>  wrote:
>
>> I don't know the reason of the silence,
>> but if anybody of the c.l.f people indeed fall sick.
>> This time the code example is attempt for resuscitation, or
>> at least to sedate your hearts.   ;-)
>
> Functional programmers write obfuscated code, too.  But unlike Perl, it
> still looks beautiful.

Ok, what i learned now, is that perception of beautifulness could be
very different.

If you would say that      sub goiter { [ map @\$_,@_ ] }
is better than my previous version, you are of course right.

Hey i say this only, so the perliatic pitbulls don't snarl to you
"that has nothing to do with perl" and tear you afterwards.

Ey. Oh, maybe i shouldn't have written this.
Brave dog. brave. search this nice ball. be a nice dog. no no no ...

But yet to something completely different:
Maybe you like the following version more.

....
# charpter 1
sub fun
{@{+ reduce { my (\$o,\$map)=@\$a; my (\$k)=\$b->[0];
my @k=exists \$map->{\$k} ? () : \$k;
[[@\$o,@k],
{ %\$map,\$k =>
[!@k?@{\$map->{\$k}}:(),@{\$b}[1..\$#\$b]] }]
} @_
}}
my (\$order,\$map)=fun [[],{}],@inp;
dump @{\$map}{@\$order};

whatever^H^H^H^H^H^H^H^H* and have fun, josef

PS: Ok, i have tried to write functional code in a imperative language.
How does look your imperative code written in a functional language?
;-)
```
 0

```Josef <e9427749@stud4.tuwien.ac.at> wrote:

> Am 08.10.2010 04:38, schrieb Ertugrul S=C3=B6ylemez:
> > Josef<e9427749@stud4.tuwien.ac.at>  wrote:
> >
> >> I don't know the reason of the silence,
> >> but if anybody of the c.l.f people indeed fall sick.
> >> This time the code example is attempt for resuscitation, or
> >> at least to sedate your hearts.   ;-)
> >
> > Functional programmers write obfuscated code, too.  But unlike Perl,
> > it still looks beautiful.
>
> Ok, what i learned now, is that perception of beautifulness could be
> very different.

Well, in fact the code I posted is beautiful in a number of ways.  It's
easy to read, very fast and also elegant.  However, it is not beautiful
in that you need to understand the concept of both Church lists and
continuation passing style (of which I've become a great fan in the last
few weeks).

In other words:  It's beautiful, if you understand the concept it
implements. =3D)

> If you would say that      sub goiter { [ map @\$_,@_ ] }
> is better than my previous version, you are of course right.

The problem is that you need to understand those Perl symbols to
understand this.  In contrast to understand my code you just need to
understand language syntax and the lambda abstraction (as well as the
concept the code implements).

> Hey i say this only, so the perliatic pitbulls don't snarl to you
> "that has nothing to do with perl" and tear you afterwards.

It does have something to do with Perl, it's just like Perl people don't
like to have their favorite language compared to others. =3D)

That's also the reason I'm still crossposting to c.l.p.m.  Of course,
readers are free to put me on their killfile, if they prefer to, but I
see no reason.

> But yet to something completely different:
> Maybe you like the following version more.
>
> ...
> # charpter 1
> sub fun
> {@{+ reduce { my (\$o,\$map)=3D@\$a; my (\$k)=3D\$b->[0];
>                my @k=3Dexists \$map->{\$k} ? () : \$k;
>                [[@\$o,@k],
>                 { %\$map,\$k =3D>
>                   [!@k?@{\$map->{\$k}}:(),@{\$b}[1..\$#\$b]] }]
>              } @_
> }}
> my (\$order,\$map)=3Dfun [[],{}],@inp;
> dump @{\$map}{@\$order};

More functional, but I still don't understand all those Perl symbols,
but I'm not a Perl programmer anyway.

> PS: Ok, i have tried to write functional code in a imperative language.
>      How does look your imperative code written in a functional language?

An extended hello world:

main :: IO ()
main =3D do
hFlush stdout
name <- getLine
printf "Hello %s!\n" name

Or an implementation of 'cat':

main :: IO ()
main =3D do
args <- getArgs
case args of
[] -> getContents >>=3D putStr
_  -> mapM_ (readFile >=3D> putStr) args

And yes, it uses constant memory space. =3D)

Greets,
Ertugrul

--=20
nightmare =3D unsafePerformIO (getWrongWife >>=3D sex)
http://ertes.de/

```
 0

```On 2010-10-08 22:22, Ertugrul S�ylemez <es@ertes.de> wrote:
> Josef <e9427749@stud4.tuwien.ac.at> wrote:
>> Am 08.10.2010 04:38, schrieb Ertugrul S�ylemez:
>> > Josef<e9427749@stud4.tuwien.ac.at>  wrote:
>> >> I don't know the reason of the silence,
>> >> but if anybody of the c.l.f people indeed fall sick.
>> >> This time the code example is attempt for resuscitation, or
>> >> at least to sedate your hearts.   ;-)
>> >
>> > Functional programmers write obfuscated code, too.  But unlike Perl,
^^^^^^^^^^
>> > it still looks beautiful.
>>
>> Ok, what i learned now, is that perception of beautifulness could be
>> very different.
>
> Well, in fact the code I posted is beautiful in a number of ways.  It's
> easy to read, very fast and also elegant.  However, it is not beautiful
^^^^^^^^^^^^

Code cannot be both "obfuscated" and "easy to read" at the same time.
"Obfuscated" means hard to read (it can still be beautiful, though).

>> If you would say that      sub goiter { [ map @\$_,@_ ] }
>> is better than my previous version, you are of course right.
>
> The problem is that you need to understand those Perl symbols to
> understand this.  In contrast to understand my code you just need to
> understand language syntax

"Those Perl symbols" are part of the language syntax. So saying you need
to understand those Perl symbols is the same as saying you just need to
understand the language syntax.

> More functional, but I still don't understand all those Perl symbols,
> but I'm not a Perl programmer anyway.

Your code also contains some syntactic elements ("those symbols") which
are not at all obvious to someone not familiar with the language (e.g.,
"->", "\", "_"). I think this is true for all languages. Some use a
large collection of non-word symbols (APL is probably the extreme case,
but Perl is also quite far along this axis), some very few (COBOL comes
to mind, but also Lisp), most are somewhere between.

hp
```
 0

```On Fri, 08 Oct 2010 19:20:10 +0200, Josef <e9427749@stud4.tuwien.ac.at> wrote:

>Am 08.10.2010 04:38, schrieb Ertugrul S�ylemez:
>> Josef<e9427749@stud4.tuwien.ac.at>  wrote:
>>
>>> I don't know the reason of the silence,
>>> but if anybody of the c.l.f people indeed fall sick.
>>> This time the code example is attempt for resuscitation, or
>>> at least to sedate your hearts.   ;-)
>>
>> Functional programmers write obfuscated code, too.  But unlike Perl, it
>> still looks beautiful.
>
>Ok, what i learned now, is that perception of beautifulness could be
>very different.
>
>If you would say that      sub goiter { [ map @\$_,@_ ] }
>is better than my previous version, you are of course right.
>
>Hey i say this only, so the perliatic pitbulls don't snarl to you
>"that has nothing to do with perl" and tear you afterwards.
>
>Ey. Oh, maybe i shouldn't have written this.
>Brave dog. brave. search this nice ball. be a nice dog. no no no ...
>
>
>But yet to something completely different:
>Maybe you like the following version more.
>
>...
># charpter 1
>sub fun
>{@{+ reduce { my (\$o,\$map)=@\$a; my (\$k)=\$b->[0];
>               my @k=exists \$map->{\$k} ? () : \$k;
>               [[@\$o,@k],
>                { %\$map,\$k =>
>                  [!@k?@{\$map->{\$k}}:(),@{\$b}[1..\$#\$b]] }]
>             } @_
>}}
>my (\$order,\$map)=fun [[],{}],@inp;
>dump @{\$map}{@\$order};
>
>whatever^H^H^H^H^H^H^H^H* and have fun, josef
>
>PS: Ok, i have tried to write functional code in a imperative language.
>     How does look your imperative code written in a functional language?
>;-)

In general, making a new hash (or array) by recopying the
original for every element in the old one, apparently seems
to takes some exponentially serious cpu time.

-sln
----------------------
use strict;
use warnings;
use Benchmark ':hireswallclock';

my \$hash = {};
for my \$multiplier ( 10 .. 20 )
{
my \$number_of_lists = \$multiplier * 100;
my \$t0 = new Benchmark;
for my \$key (1 .. \$number_of_lists)
{
\$hash->{\$key} = ['a','b'];
}
my \$t1 = new Benchmark;
print "\$number_of_lists = ".( timestr(timediff(\$t1, \$t0)) )."\n";
}

print "\n\n";

\$hash = {};
for my \$multiplier ( 10.. 20 )
{
my \$number_of_lists = \$multiplier * 100;
my \$t0 = new Benchmark;
for my \$key (1 .. \$number_of_lists)
{
\$hash = { %\$hash };
\$hash->{\$key} = ['a','b'];
}
my \$t1 = new Benchmark;
print "\$number_of_lists = ".( timestr(timediff(\$t1, \$t0)) )."\n";
}

__END__

1000 = 0.0024159 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1100 = 0.00256991 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1200 = 0.00275707 wallclock secs ( 0.02 usr +  0.00 sys =  0.02 CPU)
1300 = 0.00299716 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1400 = 0.00329781 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1500 = 0.00346112 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1600 = 0.00370002 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1700 = 0.00393891 wallclock secs ( 0.01 usr +  0.00 sys =  0.01 CPU)
1800 = 0.00404406 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
1900 = 0.00440192 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
2000 = 0.00462699 wallclock secs ( 0.02 usr +  0.00 sys =  0.02 CPU)

1000 = 0.241532 wallclock secs ( 0.23 usr +  0.00 sys =  0.23 CPU)
1100 = 0.528928 wallclock secs ( 0.53 usr +  0.00 sys =  0.53 CPU)
1200 = 0.687361 wallclock secs ( 0.69 usr +  0.00 sys =  0.69 CPU)
1300 = 0.812351 wallclock secs ( 0.81 usr +  0.00 sys =  0.81 CPU)
1400 = 0.937367 wallclock secs ( 0.94 usr +  0.00 sys =  0.94 CPU)
1500 = 1.06237 wallclock secs ( 1.06 usr +  0.00 sys =  1.06 CPU)
1600 = 1.203 wallclock secs ( 1.19 usr +  0.00 sys =  1.19 CPU)
1700 = 1.34361 wallclock secs ( 1.34 usr +  0.00 sys =  1.34 CPU)
1800 = 1.48424 wallclock secs ( 1.49 usr +  0.00 sys =  1.49 CPU)
1900 = 1.6405 wallclock secs ( 1.64 usr +  0.00 sys =  1.64 CPU)
2000 = 1.81238 wallclock secs ( 1.81 usr +  0.00 sys =  1.81 CPU)

```
 0

```Josef wrote:

> This posting is cross-posted to c.l.f only, because even some of the
> stuff in the appended code looks familiar at first, it holds
> things in it which can cause heart attacks to this guys.
> So be warned.

I saw that in c.l.f. in my main identity and thought, gosh, he needs
perl.  Did you get it squared away?
--
John Smith
```
 0

```John Smith <john@example.invalid> wrote:

> in my main identity

I suggest choosing something other than "John Smith" as others have
used that name and behaved badly, I have it killfiled.

--
email: perl -le "print scalar reverse qq/moc.liamg\100cm.j.dat/"
The above message is a Usenet post.
I don't recall having given anyone permission to use it on a Web site.
```
 0

```Am 09.10.2010 00:22, schrieb Ertugrul Söylemez:
> Josef<e9427749@stud4.tuwien.ac.at>  wrote:
>
>> Am 08.10.2010 04:38, schrieb Ertugrul Söylemez:
>>>
>>> [obfuscated code][...] But unlike Perl, it still looks beautiful.
>>
>> Ok, what i learned now, is that perception of beautifulness could be
>> very different.
>
> Well, in fact the code I posted is beautiful in a number of ways.  It's
> easy to read, very fast and also elegant. [...]

But this is elaborately demonstrated by Peter already.

> In other words:  It's beautiful, if you understand the concept it
> implements. =)

So if i understand the concept it is beautiful independent if i use

>> Hey i say this only, so the perliatic pitbulls don't snarl to you
>> "that has nothing to do with perl" and tear you afterwards.

To be honest you was not really in danger.
I said this only to tease my perl colleagues.
And i assumed that the directly following sentences
"Oh, maybe i shouldn't have written this. Brave dog. brave.
search this nice ball. be a nice dog. no no no ...
"
and their comic-like style are enough to point out the irony.

(Farther I think that the posting from Rhodri James early explains
very well, why that was happen in this thread somewhere else.)

> It does have something to do with Perl, it's just like Perl people don't
> like to have their favorite language compared to others. =)

Why you thing so?
Have you taken my speech to seriously?

And if you are unsure, how to classify perl mongers,
an old local proverb say: "Barking dogs don't bite." ;-)

BTW comparing programming languages is difficult and need normally a
deep actual knowledge of the languages in the comparsion.
AFAIR Bjarne Stroustrup utter this in his book
"The Design and Evolution of C++" (Eiffel vs. C++).

(Except if the main purpose of a language isn't programming altogether.
Then it is sometimes simply to state but often nevertheless unfair.)

And beside that how you weight LOP vs. OOP vs. FOP vs. Multi Paradigm?
And what is more important orthogonality, feature richness, DWIMery &c?
And which learning curve is preferable?
Should the language try to guide the programmer?

> That's also the reason I'm still crossposting to c.l.p.m.

So you think functional programming in perl as topic, is not
enough to crosspost? ;-)

> Of course, readers are free to put me on their killfile,
> if they prefer to, but I see no reason.

Hmm, why you say this if you see no reason?
Or do you think some perl mongers can see this differently?
But is this kind of thinking not a reason by itself?
So you contradict you again ;-)

>> But yet to something completely different:
>> Maybe you like the following version more.
>>
>> ...
>> # charpter 1
>> sub fun
>> {@{+ reduce { my (\$o,\$map)=@\$a; my (\$k)=\$b->[0];
>>                 my @k=exists \$map->{\$k} ? () : \$k;
>>                 [[@\$o,@k],
>>                  { %\$map,\$k =>
>>                    [!@k?@{\$map->{\$k}}:(),@{\$b}[1..\$#\$b]] }]
>>               } @_
>> }}
>> my (\$order,\$map)=fun [[],{}],@inp;
>> dump @{\$map}{@\$order};
>
> More functional, [..]

In what sense do you think this is more functional?
Because this version hasn't used closures?
Or maybe the use of map and filter (=grep in perl) functions in the
previous cinderella version are evil? Or recursion?

I always think this is all fine in functional programming, i'm wrong? ;-)

> but I still don't understand all those Perl symbols,
> but I'm not a Perl programmer anyway.

(I remember the meaning of the "->" *symbol* and
i think i guessed the "=>" *symbol* correctly. ;-)

bye,
Jos "not a native speaker" ef

Haskell is a nice interesting noteworthily language. ;-)

PPS: This time with extra smiley's.
```
 0

```"Peter J. Holzer" <hjp-usenet2@hjp.at> wrote:

> On 2010-10-08 22:22, Ertugrul S=C3=B6ylemez <es@ertes.de> wrote:
> > Josef <e9427749@stud4.tuwien.ac.at> wrote:
> >> Am 08.10.2010 04:38, schrieb Ertugrul S=C3=B6ylemez:
> >> > Josef<e9427749@stud4.tuwien.ac.at>  wrote:
> >> >> I don't know the reason of the silence,
> >> >> but if anybody of the c.l.f people indeed fall sick.
> >> >> This time the code example is attempt for resuscitation, or
> >> >> at least to sedate your hearts.   ;-)
> >> >
> >> > Functional programmers write obfuscated code, too.  But unlike Perl,
>                                   ^^^^^^^^^^
> >> > it still looks beautiful.
> >>
> >> Ok, what i learned now, is that perception of beautifulness could be
> >> very different.
> >
> > Well, in fact the code I posted is beautiful in a number of ways.  It's
> > easy to read, very fast and also elegant.  However, it is not beautiful
>   ^^^^^^^^^^^^
>
> Code cannot be both "obfuscated" and "easy to read" at the same time.
> "Obfuscated" means hard to read (it can still be beautiful, though).
>
> [...]
>
> "Those Perl symbols" are part of the language syntax. So saying you
> need to understand those Perl symbols is the same as saying you just
> need to understand the language syntax.

That might be your definition of "obfuscated".  Code can be hard to
understand, even if you happen to know all the language elements and
library functions it uses.  My code example is of that kind.

Greets,
Ertugrul

--=20
nightmare =3D unsafePerformIO (getWrongWife >>=3D sex)
http://ertes.de/

```
 0

```On 2010-10-12 02:37, Ertugrul S�ylemez <es@ertes.de> wrote:
> "Peter J. Holzer" <hjp-usenet2@hjp.at> wrote:
>> On 2010-10-08 22:22, Ertugrul S�ylemez <es@ertes.de> wrote:
>> > Josef <e9427749@stud4.tuwien.ac.at> wrote:
>> >> Am 08.10.2010 04:38, schrieb Ertugrul S�ylemez:
>> >> > Josef<e9427749@stud4.tuwien.ac.at>  wrote:
>> >> >> I don't know the reason of the silence,
>> >> >> but if anybody of the c.l.f people indeed fall sick.
>> >> >> This time the code example is attempt for resuscitation, or
>> >> >> at least to sedate your hearts.   ;-)
>> >> >
>> >> > Functional programmers write obfuscated code, too.  But unlike Perl,
>>                                   ^^^^^^^^^^
>> >> > it still looks beautiful.
>> >>
>> >> Ok, what i learned now, is that perception of beautifulness could be
>> >> very different.
>> >
>> > Well, in fact the code I posted is beautiful in a number of ways.  It's
>> > easy to read, very fast and also elegant.  However, it is not beautiful
>>   ^^^^^^^^^^^^
>>
>> Code cannot be both "obfuscated" and "easy to read" at the same time.
>> "Obfuscated" means hard to read (it can still be beautiful, though).
>>
>> [...]
>>
>> "Those Perl symbols" are part of the language syntax. So saying you
>> need to understand those Perl symbols is the same as saying you just
>> need to understand the language syntax.
>
> That might be your definition of "obfuscated".

Not sure what you mean by "that". My definition of "obfuscated" is
"(deliberately written to be) hard to read".

AFAIK this is the usual meaning of "obfuscated" in programming. See for
example the rules of the Obfuscated C Code Contest or the Wikipedia
article on obfuscated code. If you have a different definition, you
might want to get into the habit of posting your definition before using
the word to ensure you will be understood.

by someone familiar with the language" - every non-trivial program is
hard to read for someone who doesn't know the language)

> Code can be hard to understand, even if you happen to know all the
> language elements and library functions it uses.

Yes, of course.

> My code example is of that kind.

So it is not "easy to read", as you claimed.

hp

```
 0

```On Sep 25, 9:05=C2=A0pm, Xah Lee <xah...@gmail.com> wrote:
> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> ...

thanks all for many interesting solutions. I've been so busy in past
month on other computing issues and writing and never got around to
look at this thread. I think eventually i will, but for now just made
a link on my page to point to here.

now we have solutions in perl, python, ruby, common lisp, scheme lisp,
mathematica. I myself would also be interested in javascript perhps
i'll write one soon. If someone would go thru all these solution and
make a good summary with consistent format/names of each solution...
that'd be very useful i think. (and will learn a lot, which is how i
find this interesting)

PS here's a good site that does very useful comparisons for those
learning multiple langs.

* =E3=80=88Lisp: Common Lisp, Scheme, Clojure, Emacs Lisp=E3=80=89
http://hyperpolyglot.wikidot.com/lisp
* =E3=80=88Scripting Languages: PHP, Perl, Python, Ruby, Smalltalk=E3=
=80=89
http://hyperpolyglot.wikidot.com/scripting
* =E3=80=88Scripting Languages: Bash, Tcl, Lua, JavaScript, Io=E3=80=89
http://hyperpolyglot.wikidot.com/small
* =E3=80=88Platform Languages: C, C++, Objective C, Java, C#=E3=80=89
http://hyperpolyglot.wikidot.com/c
* =E3=80=88ML: Standard ML, OCaml, F#, Scala, Haskell=E3=80=89 http://h=
yperpolyglot.wikidot.com/ml

Xah =E2=88=91 http://xahlee.org/ =E2=98=84
```
 0

```Pascal J. Bourguignon wrote:

> Xah Lee <xahlee@gmail.com> writes:
>
>
> > here's a interesting toy list processing problem.
> >
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
> >
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
> > q r) (5 s t))
> >
> > where the first element of each sublist is the label, I need to
> > produce:
> >
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> >
> > a Mathematica solution is here:
> > http://xahlee.org/UnixResource_dir/writ/notations_mma.html
> >
> > R5RS Scheme lisp solution:
> > http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work
> > _gmail.scm by Sourav Mukherjee
> >
> > also, a Common Lisp solution can be found here:
> > ed8824bc750b?
>
> It's too complex. Just write:
>
> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
>               (2 o p) (4 q r) (5 s t))))
>
>   (mapcar (lambda (class) (reduce (function append) class :key
> (function rest)))
> (com.informatimago.common-lisp.list:equivalence-classes list :key
> (function first)))
>
>    )
>
> --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))

Clojure:

(def groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)(4 m n)
(2 o p)(4 q r) (5 s t)))

Using group-by:

(map (fn[[k v]](flatten (map rest v))) (group-by first groups))

Using reduce:

(map #(flatten(rest %)) (reduce (fn[h [k & v]]
(merge-with concat h {k v})) {} groups))

```
 0

```Στις 10/2/2011 11:03 μμ, ο/η WJ έγραψε:
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
>>  >  q r) (5 s t))
>>  >

# Here is your 2 lines Perl solution my friend

my \$i=0;
my %R;
my \$Output;
my \$Inpout =
[
[0, 'a', 'b'],
[1, 'c', 'd'],
[2, 'e', 'f'],
[3, 'g', 'h'],
[1, 'i', 'j'],
[2, 'k', 'l'],
[4, 'm', 'n'],
[2, 'o', 'p'],
[4, 'q', 'r'],
[5, 's', 't'],
];

foreach (@{\$Inpout})   { push @{\$R{\$_->[0]}}, @{\$_}[1..\$#{\$_}] }
foreach (sort keys %R) { \$Output->[\$i++] = \$R{\$_}}

use Data::Dumper; print Dumper(\$Output);

```
 0

```Στις 10/2/2011 11:03 μμ, ο/η WJ έγραψε:
> Pascal J. Bourguignon wrote:
>
>> Xah Lee<xahlee@gmail.com>  writes:
>>
>>
>>> here's a interesting toy list processing problem.
>>>
>>> I have a list of lists, where each sublist is labelled by
>>> a number. I need to collect together the contents of all sublists
>>> sharing
>>> the same label. So if I have the list
>>>
>>> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
>>> q r) (5 s t))
>>>
>>> where the first element of each sublist is the label, I need to
>>> produce:
>>>
>>> output:
>>> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>>>
>>> a Mathematica solution is here:
>>> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>>>
>>> R5RS Scheme lisp solution:
>>> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work
>>> _gmail.scm by Sourav Mukherjee
>>>
>>> also, a Common Lisp solution can be found here:
>>> ed8824bc750b?
>>
>> It's too complex. Just write:
>>
>> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
>>                (2 o p) (4 q r) (5 s t))))
>>
>>    (mapcar (lambda (class) (reduce (function append) class :key
>> (function rest)))
>> (com.informatimago.common-lisp.list:equivalence-classes list :key
>> (function first)))
>>
>>     )
>>
>> -->  ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> Clojure:
>
> (def groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)(4 m n)
> (2 o p)(4 q r) (5 s t)))
>
> Using group-by:
>
> (map (fn[[k v]](flatten (map rest v))) (group-by first groups))
>
> Using reduce:
>
> (map #(flatten(rest %)) (reduce (fn[h [k&  v]]
>    (merge-with concat h {k v})) {} groups))
>

# Here is your 2 line solution my friend

my \$i=0;
my %R;
my \$Output;
my \$Inpout =
[
[0, 'a', 'b'],
[1, 'c', 'd'],
[2, 'e', 'f'],
[3, 'g', 'h'],
[1, 'i', 'j'],
[2, 'k', 'l'],
[4, 'm', 'n'],
[2, 'o', 'p'],
[4, 'q', 'r'],
[5, 's', 't'],
];

foreach (@{\$Inpout})   { push @{\$R{\$_->[0]}}, @{\$_}[1..\$#{\$_}] }
foreach (sort keys %R) { \$Output->[\$i++] = \$R{\$_}}

use Data::Dumper; print Dumper(\$Output);

```
 0

```Στις 10/2/2011 11:03 μμ, ο/η WJ έγραψε:
> Pascal J. Bourguignon wrote:
>
>> Xah Lee<xahlee@gmail.com>  writes:
>>
>>
>>> here's a interesting toy list processing problem.
>>>
>>> I have a list of lists, where each sublist is labelled by
>>> a number. I need to collect together the contents of all sublists
>>> sharing
>>> the same label. So if I have the list
>>>
>>> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
>>> q r) (5 s t))
>>>
>>> where the first element of each sublist is the label, I need to
>>> produce:
>>>
>>> output:
>>> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>>>
>>> a Mathematica solution is here:
>>> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>>>
>>> R5RS Scheme lisp solution:
>>> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work
>>> _gmail.scm by Sourav Mukherjee
>>>
>>> also, a Common Lisp solution can be found here:
>>> ed8824bc750b?
>>
>> It's too complex. Just write:
>>
>> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
>>                (2 o p) (4 q r) (5 s t))))
>>
>>    (mapcar (lambda (class) (reduce (function append) class :key
>> (function rest)))
>> (com.informatimago.common-lisp.list:equivalence-classes list :key
>> (function first)))
>>
>>     )
>>
>> -->  ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> Clojure:
>
> (def groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)(4 m n)
> (2 o p)(4 q r) (5 s t)))
>
> Using group-by:
>
> (map (fn[[k v]](flatten (map rest v))) (group-by first groups))
>
> Using reduce:
>
> (map #(flatten(rest %)) (reduce (fn[h [k&  v]]
>    (merge-with concat h {k v})) {} groups))
>

my \$i=0;
my %R;
my \$Output;
my \$Inpout =
[
[0, 'a', 'b'],
[1, 'c', 'd'],
[2, 'e', 'f'],
[3, 'g', 'h'],
[1, 'i', 'j'],
[2, 'k', 'l'],
[4, 'm', 'n'],
[2, 'o', 'p'],
[4, 'q', 'r'],
[5, 's', 't'],
];

foreach (@{\$Inpout})   { push @{\$R{\$_->[0]}}, @{\$_}[1..\$#{\$_}] }
foreach (sort keys %R) { \$Output->[\$i++] = \$R{\$_}}

use Data::Dumper; print Dumper(\$Output);

```
 0

```"WJ" <w_a_x_man@yahoo.com> wrote:
>Pascal J. Bourguignon wrote:
>
>> Xah Lee <xahlee@gmail.com> writes:

+-------------------+             .:\:\:/:/:.
|   PLEASE DO NOT   |            :.:\:\:/:/:.:
|  FEED THE TROLLS  |           :=.' -   - '.=:
|                   |           '=(\ 9   9 /)='
|   Thank you,      |              (  (_)  )
|       Management  |              /`-vvv-'\
+-------------------+             /         \
|  |        @@@          / /|,,,,,|\ \
|  |        @@@         /_//  /^\  \\_\
@x@@x@        |  |         |/         WW(  (   )  )WW
\||||/        |  |        \|           __\,,\ /,,/__
\||/         |  |         |      jgs (______Y______)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

jue
```
 0

```In Qi

(35-) (group [[0 a b] [1 c d] [2 e f] [3 g h] [1 i j]
[2 k l] [4 m n] [2 o p] [4 q r] [5 s t]])
[[a b] [g h] [c d i j] [e f k l o p] [m n q r] [s t]]

Program is:

(define group
L -> (map (grouph L) (rd (map head L))))

(define grouph
[] _ -> []
[[X | Y] | Z] X -> (append Y (grouph Z X))
[_ | Y] X -> (grouph Y X))

(define rd
[] -> []
[X | Y] -> (if (element? X Y) (rd Y) [X | (rd Y)]))

Couldn't post this under OP because this option was not given under

Mark
```
 0
Reply dr.mtarver (661) 2/14/2011 1:32:36 PM

```Xah Lee wrote:

> here's a interesting toy list processing problem.
>
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>
> where the first element of each sublist is the label, I need to
> produce:
>
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>

Solving without hash-tables or "group-by".

Using Guile:

First, sort the groups by the numbers.

(stable-sort groups (lambda(a b)(< (car a) (car b))))

((0 a b) (1 c d) (1 i j) (2 e f) (2 k l) (2 o p) (3 g h)
(4 m n) (4 q r) (5 s t))

Next, flatten the list.

(append-map identity step1)

(0 a b 1 c d 1 i j 2 e f 2 k l 2 o p 3 g h 4 m n 4 q r 5 s t)

Remove duplicate numbers.

(delete-duplicates step2)

(0 a b 1 c d i j 2 e f k l o p 3 g h 4 m n q r 5 s t)

We now need a very useful function called "scan".

;; Yields sublists of contiguous items that satisfy func.
(define (scan func lst)
(let ((tail (find-tail func lst)))
(if tail
(cons (take-while func tail)
(scan func (drop-while func tail)))
'())))

(scan symbol? step3)

((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
```
 0

```>
> Using Guile:

From Ruby to Clojure to Scheme. I think we can see where this is
heading, and I am sure I am not the only one wondering if you will be
able to find a MACLISP compiler that runs on the x86 architecture.
```
 0

```On Feb 17, 12:33=A0pm, TheFlyingDutchman <zzbba...@aol.com> wrote:
> > Using Guile:
>
> From Ruby to Clojure to Scheme. I think we can see where this is
> heading, and I am sure I am not the only one wondering if you will be
> able to find a MACLISP compiler that runs on the x86 architecture.

x86? Z8000 more probably :)

Cheers
--
MA
```
 0
Reply marcoxa1 (989) 2/17/2011 12:02:05 PM

```"WJ" <w_a_x_man@yahoo.com> wrote:
>Xah Lee wrote:

+-------------------+             .:\:\:/:/:.
|   PLEASE DO NOT   |            :.:\:\:/:/:.:
|  FEED THE TROLLS  |           :=.' -   - '.=:
|                   |           '=(\ 9   9 /)='
|   Thank you,      |              (  (_)  )
|       Management  |              /`-vvv-'\
+-------------------+             /         \
|  |        @@@          / /|,,,,,|\ \
|  |        @@@         /_//  /^\  \\_\
@x@@x@        |  |         |/         WW(  (   )  )WW
\||||/        |  |        \|           __\,,\ /,,/__
\||/         |  |         |      jgs (______Y______)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

jue
```
 0
Reply jurgenex (460) 2/18/2011 1:24:24 AM

```WJ wrote:

> Xah Lee wrote:
>
> > here's a interesting toy list processing problem.
> >
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
> >
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
> > q r) (5 s t))
> >
> > where the first element of each sublist is the label, I need to
> > produce:
> >
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> >
>
> Solving without hash-tables or "group-by".
>
> Using Guile:
>

(define groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)
(4 m n) (2 o p)(4 q r) (5 s t)))

(define keys (delete-duplicates (map car groups)))

(define (meld groups) (apply append (map cdr groups)))

(map (lambda (k)
(meld (filter (lambda (x)(eq? k (car x))) groups)))
keys)

((a b)
(c d i j)
(e f k l o p)
(g h)
(m n q r)
(s t))

```
 0

```You can just flatten the list using itertools and collate the results using=
defaultdict:

import itertools
from collections import defaultdict

sequence =3D ((0,'a','b'),(1,'c','d'),(2,'e','f'),(3,'g','h'),(1,'i','j'),(=
2,'k','l'),(4,'m','n'),(2,'o','p'),(4,'q','r'),(5,'s','t'))

# flatten the list to (0,'a','b',1,'c','d'...
chain =3D itertools.chain.from_iterable(sequence)
# use defaultdict to set up the final list and deal with initial empty dict=
ionary key
final_list =3D defaultdict(list)
for i in chain:
if isinstance(i, int):
number =3D i
else:
final_list[number].append(i)
print (final_list.items())

HTH,

Nick

On Sunday, September 26, 2010 2:05:13 PM UTC+10, Xah Lee wrote:
> here's a interesting toy list processing problem.
>=20
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>=20
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>=20
> where the first element of each sublist is the label, I need to
> produce:
>=20
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>=20
> a Mathematica solution is here:
> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>=20
> R5RS Scheme lisp solution:
> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gmai=
l.scm
> by Sourav Mukherjee
>=20
> also, a Common Lisp solution can be found here:
4bc750b?
>=20
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.
>=20
>  Xah =E2=88=91 xahlee.org =E2=98=84
```
 0
Reply thebalancepro (29) 2/6/2013 11:03:09 AM

```Python 3 version:

from collections import defaultdict

data =3D ((0,'a','b'),(1,'c','d'),(2,'e','f'),(3,'g','h'),(1,'i','j'),(2,'k=
','l'),(4,'m','n'),(2,'o','p'),(4,'q','r'),(5,'s','t'))

register =3D defaultdict(list)
for number, *letters in data:
register[number].extend(letters)
final =3D []
for i in sorted(register.keys()):
final.append(register[i])
print (final)

NB sorting is "stable" in Python, so sorted() will always keep the 1's, 2's=
etc in the same order as they were in the unsorted list.

Nick

On Sunday, 26 September 2010 14:05:13 UTC+10, Xah Lee  wrote:
> here's a interesting toy list processing problem.
>=20
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
>=20
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
>=20
> where the first element of each sublist is the label, I need to
> produce:
>=20
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>=20
> a Mathematica solution is here:
> http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>=20
> R5RS Scheme lisp solution:
> http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gmai=
l.scm
> by Sourav Mukherjee
>=20
> also, a Common Lisp solution can be found here:
4bc750b?
>=20
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.
>=20
>  Xah =E2=88=91 xahlee.org =E2=98=84
```
 0
Reply thebalancepro (29) 2/6/2013 11:25:36 PM

```Oops! Not that sort stability is used in this algorithm. Was thinking of so=
mething else :-)

N

On Thursday, 7 February 2013 10:25:36 UTC+11, Nick Mellor  wrote:
> Python 3 version:
>=20
>=20
>=20
> from collections import defaultdict
>=20
>=20
>=20
> data =3D ((0,'a','b'),(1,'c','d'),(2,'e','f'),(3,'g','h'),(1,'i','j'),(2,=
'k','l'),(4,'m','n'),(2,'o','p'),(4,'q','r'),(5,'s','t'))
>=20
>=20
>=20
> register =3D defaultdict(list)
>=20
> for number, *letters in data:
>=20
>     register[number].extend(letters)
>=20
> final =3D []
>=20
> for i in sorted(register.keys()):
>=20
>     final.append(register[i])
>=20
> print (final)
>=20
>=20
>=20
> NB sorting is "stable" in Python, so sorted() will always keep the 1's, 2=
's etc in the same order as they were in the unsorted list.
>=20
>=20
>=20
> Nick
>=20
>=20
>=20
> On Sunday, 26 September 2010 14:05:13 UTC+10, Xah Lee  wrote:
>=20
> > here's a interesting toy list processing problem.
>=20
> >=20
>=20
> > I have a list of lists, where each sublist is labelled by
>=20
> > a number. I need to collect together the contents of all sublists
>=20
> > sharing
>=20
> > the same label. So if I have the list
>=20
> >=20
>=20
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
>=20
> > r) (5 s t))
>=20
> >=20
>=20
> > where the first element of each sublist is the label, I need to
>=20
> > produce:
>=20
> >=20
>=20
> > output:
>=20
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>=20
> >=20
>=20
> > a Mathematica solution is here:
>=20
> > http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>=20
> >=20
>=20
> > R5RS Scheme lisp solution:
>=20
> > http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_gm=
ail.scm
>=20
> > by Sourav Mukherjee
>=20
> >=20
>=20
> > also, a Common Lisp solution can be found here:
>=20
824bc750b?
>=20
> >=20
>=20
> > anyone care to give a solution in Python, Perl, javascript, or other
>=20
> > lang? am guessing the scheme solution can be much improved... perhaps
>=20
> > using some lib but that seems to show scheme is pretty weak if the lib
>=20
> > is non-standard.
>=20
> >=20
>=20
> >  Xah =E2=88=91 xahlee.org =E2=98=84

```
 0
Reply thebalancepro (29) 2/6/2013 11:37:26 PM

73 Replies
32 Views