From: Xah Lee
Subject: tree functions daily exercise
Date: 
Message-ID: <1115969822.361451.100620@g47g2000cwa.googlegroups.com>
Dear functional programers,

i run services called a-python-a-day and a-java-a-day, where each day i
give a tip or snippet of code in these languages, also as a way for me
to learn these languages.

I've been running this perl-python a-day mailing list for several
months, and have accumulated a sizable tutorial here:
http://xahlee.org/perl-python/python.html

In the coming days, i'll be starting to translate a complete set of
tree processing functions. These functions, always takes a tree as
input (arbitrary nested list) and always returns a list of a definite
structure. Together, they form a particular functional programing
paradigm. See this page for the complete documentation as it exists
now:
http://xahlee.org/PerlMathematica_dir/Matica.html

As usuall, each day we will be spending about 20 minutes enjoying these
little exercises. If past experience is a good indication, then i
presume that in a month or two we will have built a complete set of
functions that manipulates tress, in languages Python and Java and
Perl. (the Perl set is already written)

I'm always interested in LISP and Haskell languages, but never
seriously learned them. I'm hoping that you functional programers in
these languages or learners, join me in these 15 minutes daily
exercises as a fun routine to learn languages or functional programing.

I'm in particular very interested in the daily discussions of these
topics by functional programers, as well seeing such set of complete
code in scsh and Haskell. (Common Lisp or other functional languages
are always welcome of course)

  Xah
  ···@xahlee.org
∑ http://xahlee.org/

From: Ketil Malde
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <87r7gbr1rg.fsf@sefirot.ii.uib.no>
"Xah Lee" <···@xahlee.org> writes:

> I'm always interested in LISP and Haskell languages, but never
> seriously learned them. I'm hoping that you functional programers in
> these languages or learners, join me in these 15 minutes daily
> exercises as a fun routine to learn languages or functional programing.

From the Perl documentation, I think Range and Table already exist in
Haskell.

  range x y = [x..y]
  range' x y step = [x,x+step..y]

  table f x y = map f [x..y]

and so on.

For trees, you would need a data structure (you can't nest lists
arbitrarily):

  data Tree a = Leaf a | Branch (Tree a) (Tree a)

Read: "a tree over a type a is either a leaf containing an a, or a branch
containing two (sub)trees over a"

and then:

  depth (Leaf a) = 1   -- or perhaps 0?
  depth (Branch left right) = 1 + max (depth left) (depth right)

(untested)

If you want to discuss how to achieve something in e.g. Haskell,
please post it here (c.l.f), and I'll try to answer.  I know that I'll
forget to check your (or anybody else's) web site :-)

-kzm
-- 
If I haven't seen further, it is by standing in the footprints of giants
From: ···@xahlee.org
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <1115974325.071477.299180@g49g2000cwa.googlegroups.com>
the following is the first post...

----------

Today we'll be writing a function called Range. The Perl documentation
is as follows.

Perl & Python & Java Solutions will be posted in 48 hours.

This is Perl-Python a-day. See
http://xahlee.org/web/perl-pyt hon/python.html

  Xah
  ····@xahlee.org
∑ http://xahlee.org/

--------------------------

Range

     Range($iMax) generates the list [1, 2, ... , $iMax].

     Range($iMin, $iMax) generates the list [$iMin, ... , $iMax].

     Range($iMin, $iMax, $iStep) uses increment $iStep, with the last
element
     in the result being less or equal to $iMax. $iStep cannot be 0. If

     $iStep is negative, then the role of $iMin and $iMax are reversed.


     If Range fails, 0 is returned.

     Example:

      Range(5); # returns [1,2,3,4,5]

      Range(5,10); # returns [5,6,7,8,9,10]

      Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]

      Range( 5, -4, -2); # returns [5,3,1,-1,-3]
From: Bruce Lewis
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <nm9y8aj6xd3.fsf@mass-toolpike.mit.edu>
Xah, your description does not match your examples.  It pays to write
your solution in a language that can closely follow your description, so
that such errors can be easily found.  I used Scheme.

···@xahlee.org writes:

>      Range($iMax) generates the list [1, 2, ... , $iMax].

So far so good.

(define (range1 end)
  (range3 1 end 1))

>      Range($iMin, $iMax) generates the list [$iMin, ... , $iMax].

Again, no problem.

(define ascending? <)
(define (range2 start end)
  (range3 start end (if (ascending? start end) 1 -1)))


>      Range($iMin, $iMax, $iStep) uses increment $iStep, with the last
> element
>      in the result being less or equal to $iMax. $iStep cannot be 0. If
> 
>      $iStep is negative, then the role of $iMin and $iMax are reversed.

Here is your English translated into Scheme.  Note the place where the
role of start ($iMin) and end ($iMax) are reversed.

(define (range3 start end increment)
  (if (negative? increment)
      (range3 end start (- increment))
      (if (ascending? end start)
          (list)
          (cons start (range3 (+ start increment) end increment)))))

Your last example doesn't work.  Here's a helper function to make my
examples more closely mirror yours:

(define (range . args)
  (apply
   (case (length args)
     ((1) range1)
     ((2) range2)
     ((3) range3))
   args))

>      Example:
> 
>       Range(5); # returns [1,2,3,4,5]

(range 5)  ; likewise returns (1 2 3 4 5)

>       Range(5,10); # returns [5,6,7,8,9,10]

(range 5 10)  ; likewise returns (5 6 7 8 9 10)

>       Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]

(range 5 7 3/10)  ; likewise returns (5 53/10 28/5 59/10 31/5 13/2 34/5)

>       Range( 5, -4, -2); # returns [5,3,1,-1,-3]

(range 5 -4 -2)  ; instead returns (-4 -2 0 2 4)

If your last example is correct, then you didn't really mean to say that
the role of $iMin and $iMax would be reversed.  You should change the
description accordingly, and likely change the variable names since
$iMin suggests a variable that must be less than or equal to $iMax.
From: Ketil Malde
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <87fywrqys1.fsf@sefirot.ii.uib.no>
···@xahlee.org writes:

>      If Range fails, 0 is returned.

Surely an empty list is a better choice?

-kzm
-- 
If I haven't seen further, it is by standing in the footprints of giants
From: Xah Lee
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <1115976937.917496.55720@g47g2000cwa.googlegroups.com>
Yes you are right.

it was 0 because Perl doesn't have lists, and support it by memory
addresses... i.e. one can't have a empty list in perl... (in
Mathematica, if the argument is wrong, the whole thing is returned
verbatim with error messages as a side effect)

my spec and that Perl module was written in 1998 and in a incomplete
state. Parts needs to be editted or improved when applied to various
other lang...

 Xah
 ···@xahlee.org
∑ http://xahlee.org/

Ketil Malde wrote:
> ···@xahlee.org writes:
>
> >      If Range fails, 0 is returned.
>
> Surely an empty list is a better choice?
>
> -kzm
> --
> If I haven't seen further, it is by standing in the footprints of
giants
From: Jussi Piitulainen
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <qot8y2j1kpg.fsf@venus.ling.helsinki.fi>
Xah Lee writes:

> my spec and that Perl module was written in 1998 and in a incomplete
> state. Parts needs to be editted or improved when applied to various
> other lang...

Here's my entry for Scheme. I changed the spec to suit the language,
took the problem as an exercise in floor/ceiling calculations, used
Graham-Knuth-Patashnik as reference, and was pleasantly surprised when
the branches for positive and negative s turned out identical.

;;; Increasing list of b+ks in the interval [b..e) if s > 0.
;;; Decreasing list of b+ks in the interval (e..b] if s < 0.

(define (range b e s)
  (do ((k (- (ceiling (/ (- e b) s)) 1) (- k 1))
       (r '() (cons (+ b (* k s)) r)))
      ((< k 0) r)))
From: David Formosa (aka ? the Platypus)
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <slrnd8mda5.4ns.dformosa@dformosa.zeta.org.au>
On 13 May 2005 02:35:37 -0700, Xah Lee <···@xahlee.org> wrote:
> Yes you are right.
> 
> it was 0 because Perl doesn't have lists, and support it by memory
> addresses... i.e. one can't have a empty list in perl...

Please don't beleave anything that Xah Lee says about Perl.  
Perl has native support for lists.
Perl doesn't support lists by memory address (whatever that means)
It is possable to have an empty list in perl.

-- 
Please excuse my spelling as I suffer from agraphia. See
http://dformosa.zeta.org.au/~dformosa/Spelling.html to find out more.
Free the Memes.
From: ···@xahlee.org
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <1115974944.431553.286170@f14g2000cwb.googlegroups.com>
hi Ketil,

Thanks for the response.
I forgot to post the first message here in comp.lang.functional.

The first exercise is Range(). it is built in in most languages.

btw, most of these are from the language Mathematica. (trade mark or
otherwise properties of Wolfram Research Incorporated) Many of these
functions are in many other functional languages, but the Mathematica
version tends to be more general. (i.e. includes options that applies
to a level of a tree, a reverse level (counting from leaves), or a set
of levels, or multiple parts of the tree. i.e. stardard forms
Mathematica calls Level Spec, Part spec ...)

umm... what's the easiest way to get Haskell to run on OS X? (starts
looking...)

 Xah
 ···@xahlee.org
∑ http://xahlee.org/



Ketil Malde wrote:
> "Xah Lee" <···@xahlee.org> writes:
>
> > I'm always interested in LISP and Haskell languages, but never
> > seriously learned them. I'm hoping that you functional programers
in
> > these languages or learners, join me in these 15 minutes daily
> > exercises as a fun routine to learn languages or functional
programing.
>
> From the Perl documentation, I think Range and Table already exist in
> Haskell.
>
>   range x y = [x..y]
>   range' x y step = [x,x+step..y]
>
>   table f x y = map f [x..y]
>
> and so on.
>
> For trees, you would need a data structure (you can't nest lists
> arbitrarily):
>
>   data Tree a = Leaf a | Branch (Tree a) (Tree a)
>
> Read: "a tree over a type a is either a leaf containing an a, or a
branch
> containing two (sub)trees over a"
>
> and then:
>
>   depth (Leaf a) = 1   -- or perhaps 0?
>   depth (Branch left right) = 1 + max (depth left) (depth right)
>
> (untested)
>
> If you want to discuss how to achieve something in e.g. Haskell,
> please post it here (c.l.f), and I'll try to answer.  I know that
I'll
> forget to check your (or anybody else's) web site :-)
>
> -kzm
> --
> If I haven't seen further, it is by standing in the footprints of
giants
From: Stefan Holdermans
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <Pine.GSO.4.44.0505150933070.410-100000@bellatrix.students.cs.uu.nl>
On 13 May 2005 ···@xahlee.org wrote:
Xah,

> The first exercise is Range(). it is built in in most languages.

Let's try in Haskell.

First, we have to decide how to represent trees. From your description
of lists, the following data type seems appropriate:

  type Forest = [Tree a]
  data Tree a = Leaf a | Branch [Tree a]

So, what you call tree will in fact be a forest of multiway branching
leaf trees.

Your function Range can take one, two, or three numerical arguments. Let's
blend these options into one type for range specifications:

  data (Num a, Enum a) => RangeSpec a = To a
                                      | FromTo a a
                                      | FromToWith a a a

Range specifications are parameterized by the type of the tree elements.
Our range function will work for types that are numeric and enumberable,
hence the class constraints on RangeSpec.

Now we write a function range' that takes a range specification and
returns a list that corresponds to the specified range.

  range' :: (Num a, Enum a) => RangeSpec a -> [a]

We implement this function using the sugared incarnations of the
enumFromTo and enumFromThenTo methods of the Enum class:

  range' (To a)                = [toEnum 1 .. a]
  range' (FromTo a1 a2)        = [a1 .. a2]
  range' (FromToWith a1 a2 a3) = [a1, a1 + a3 .. a2]

Finally, we wrap range' in the function range that produces a tree instead
of a list:

  range :: (Num a, Enum a) => RangeSpec a -> Forest a
  range =  map Leaf . range'

See http://www.students.cs.uu.nl/~sholderm/downloads/Treematica.tar.gz.

Regards,

Stefan

-----
http://www.students.cs.uu.nl/~sholderm/
http://www.students.cs.uu.nl/~sholderm/blog/
From: ···@xahlee.org
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <1116236529.172707.174570@g47g2000cwa.googlegroups.com>
K!
http://en.wikipedia.org/wiki/K_programming_language

Interesting.
Looking at your program, they are so short. I don't know if they are
full implementation or what...

Btw, the functions listed at
 http://xahlee.org/PerlMathematica_dir/Matica.html
are motly from Mathematica, except the Tree Index Set Utilities:
   RandomIndexSet, LeavesIndexSet, NonleavesIndexSet, MinimumIndexSet,
   CompleteIndexSet, IndexSetSort, TreeToIndexSet, IndexSetToTree

which isn't trivial to code. (nor is it trivial for some of the
Mathematica functions)
the complete documentation can be seen online
http://documents.wolfram.com/mathematica/

 Xah
 ···@xahlee.org
∑ http://xahlee.org/


sa wrote:
> xah:
>
> i've provided k implementations here:
>
>     http://www.nsl.com/k/xah.k
>
> of a dozen or so of the functions in your toolkit.  many are trivial,
> since they're simply k primitives.  e.g. transpose is just +:
>
> here are some of the definitions (the script contains test-examples
> as well):
>
> range1:!:
> range2:{x+!1+y-x}
> range3:{x+z*!1+_(y-x)%z}
> depth:{:[(@x)|~#x;0;1+|/_f'x]}
> leaves:,//
> ·················@
> leafpaths:{:[@x;,();,/(!#x),/:'_f'x]}
> subpaths:{(1+!#x)#\:x}
> nonleafpaths:?,·······················@
> ··························@
> nodecount:+/(leafcount;nonleafcount)@\:
> dimensions:^:
> part:.
> transpose:+:
> apply:{y{x'}/x}
> flattenat:{apply[,/;y]x}
> rotateleft:1!
>
> my immediate reaction is that a well-designed set of primitives
> obviates the need for such a toolkit.
> 
> nb: i've eliminated the newsgroup crossposting.
From: Joachim Durchholz
Subject: Re: tree functions daily exercise
Date: 
Message-ID: <d6c4ta$lpd$1@online.de>
···@xahlee.org wrote:
 > K!
 > http://en.wikipedia.org/wiki/K_programming_language
 >
 > Interesting.
 > Looking at your program, they are so short. I don't know if they are
 > full implementation or what...

That's no surprise: list and tree processing are often built right into 
more expressive languages, and K seems to be one of these.

Regards,
Jo
From: Xah Lee
Subject: Re: tree functions daily exercise: Range
Date: 
Message-ID: <1118613721.423843.39090@g43g2000cwa.googlegroups.com>
Here's the belated Java version.

import java.util.List;
import java.util.ArrayList;
import java.lang.Math;

class math {
    public static List range(double n) {
        return range(1,n,1);
    }

    public static List range(double n, double m) {
        return range(n,m,1);
    }

    public static List range(double iMin, double iMax, double iStep) {
        List ll = new ArrayList();
        if (iMin <= iMax && iStep > 0) {
            for (int i=0; i <= Math.floor((iMax-iMin)/iStep); i++) {
                ll.add(new Double(iMin+i*iStep));
            }
            return ll;
        }
        if (iMin >= iMax && iStep < 0) {
            for (int i=0; i <= Math.floor((iMin-iMax)/-iStep); i++) {
                ll.add(new Double(iMin+i*iStep));
            }
            return ll;
        }
        // need to raise exception here
        return ll;
    }
}

class Range {
    public static void main(String[] arg) {
        System.out.println(math.range(5));
        System.out.println(math.range(5,10));
        System.out.println(math.range(5,7, 0.3));
        System.out.println(math.range(5,-4, -2));
    }
}

Perl & Python versions archived here:
http://xahlee.org/tree/tree.html

 Xah
 ···@xahlee.org
∑ http://xahlee.org/


Dear functional programers,

i run services called a-python-a-day and a-java-a-day, where each day i

 give a tip or snippet of code in these languages, also as a way for me

 to learn these languages.

I've been running this perl-python a-day mailing list for several
 months, and have accumulated a sizable tutorial here:
http://xahlee.org/perl-python/python.html

In the coming days, i'll be starting to translate a complete set of
 tree processing functions. These functions, always takes a tree as
 input (arbitrary nested list) and always returns a list of a definite
 structure. Together, they form a particular functional programing
 paradigm. See this page for the complete documentation as it exists
 now:
http://xahlee.org/PerlMathemat ica_dir/Matica.html

As usuall, each day we will be spending about 20 minutes enjoying these

 little exercises. If past experience is a good indication, then i
 presume that in a month or two we will have built a complete set of
 functions that manipulates tress, in languages Python and Java and
 Perl. (the Perl set is already written)

I'm always interested in LISP and Haskell languages, but never
 seriously learned them. I'm hoping that you functional programers in
 these languages or learners, join me in these 15 minutes daily
 exercises as a fun routine to learn languages or functional
programing.

I'm in particular very interested in the daily discussions of these
 topics by functional programers, as well seeing such set of complete
 code in scsh and Haskell. (Common Lisp or other functional languages
 are always welcome of course)

  Xah 
   ····@xahlee.org 
 ∑ http://xahlee.org/
From: Xah Lee
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <1118616214.185026.125240@z14g2000cwz.googlegroups.com>
Here's the next tree functions exercise in Python, Perl, Java. Other
language solutions welcome.
http://xahlee.org/tree/tree.html
---------------------

 Table('exprString', [iMax]) generates a list of iMax copies of value
of
    eval('exprString'), and returns the refence to the list. i.e.
    [eval('exprString'),eval('exprString'),...]

    Table('exprString', ['i', iMax]) generates a list of the values by
    evaluating 'exprString' when 'i' in the string runs from 1 to iMax.

    Table('exprString', ['i', iMin, iMax]) starts with 'i' = iMin.

    Table('exprString', ['i', iMin, iMax, iStep]) uses steps iStep. If
iStep
    is negative, then the role of iMin and iMax are reversed. Inputs
such as
    [1, -3 , 1] returns bad result.

    Table('exprString', ['i', iMin, iMax, iStep], ['j', jMin, jMax,
iStep],
    ... ) gives a array by iterating 'i', 'j' in 'exprString'. For
example,
    Table('f(i,j)', ['i',1,3], ['j',5,6]) returns [[f(1, 5), f(1, 6)],
[f(2,
    5), f(2, 6)], [f(3, 5), f(3, 6)]].

    In general, Table has the form Table('expressionString', iterator1,
    iterator2, ...) where 'expressionString' is a string that will be
    evaluated by eval. iterator have one of the following forms [iMax],
    ['dummyVarString',iMax], ['dummyVarString',iMin, iMax], or
    ['dummyVarString',iMin, iMax, iStep].

    If Table fails, 0 is returned. Table can fail, for example, when
the
    argument are not appropriate references or the iterator range is
bad
    such as ['i',5,1].

    Example:

     Table('q(s)' ,[3]); # returns ['s','s','s']

     Table( 'i**2' , ['i', 4]); # returns [1, 4, 9, 16]

     Table('[i,j,k]',['i',2],['j',100,200,100],['k',5,6])
     # returns [[[[1,100,5],[1,100,6]],[[1,200,5],[1,200,6]]],
     #          [[[2,100,5],[2,100,6]],[[2,200,5],[2,200,6]]]]


Wolfram Research's Table function documentation is at:
http://documents.wolfram.com/mathematica/functions/Table
(this post is not affliated with Wolfram Research Incorporated and has
not been approved by Wolfram Research Incorporated.)

The first argument of Table function in Mathematica (mma) is a
expression. Most other languages cannot have such symbolic expressions.
In Perl, a string is choosen instead as the experssion, and it is being
evalutade later as code. This may not be a practical choice but anyway
it's just a exercise. Each other language should choose appropriate
design for this emulation...

Perl, Python, Java solutions will be posted by me in the coming days.

 Xah
 ···@xahlee.org
∑ http://xahlee.org/
From: Xah Lee
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <1119075460.194633.144820@g14g2000cwa.googlegroups.com>
The Perl version of the Tree function is posted. It's a bit long.
Please see the code here:
http://xahlee.org/tree/Table.html

the choice of having a string as the first argument to Table is a bit
awkward in Perl. Possibly i'll have to rewrite it so that the first
argument is a function instead, where in each iteration the the
variables are fed to the function. This necessarily breaks the
Mathematica's syntactical form of Table, and is slightly less flexible
in power, but is more natural and practical in non-symbolic languages
like Perl, Python, Java.

I think the goal of the whole tree functions project
http://xahlee.org/tree/tree.html
would make the code actually practically useful for processing trees in
each language, as opposed to sticking to uniformness of these functions
across languages.

later on, as we write more tree functions, the whole set will be very
useful in processing tree structures, such as XML and many other things
spurn from it today.

Disclaimer: this project is not affiliated with Wolfram Research Inc.

 Xah
 ···@xahlee.org
∑ http://xahlee.org/
From: Xah Lee
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <1119344096.341769.66760@f14g2000cwb.googlegroups.com>
here's the Python spec for the Table function:

    '''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the
range range(iStart,iEnd,iStep).
Example: Table(f,[3,10,2]) returns [f(3),f(5),f(7),f(9)]
Table(f,[iStart,iEnd,iStep], [jStart,jEnd,jStep], ...) returns a nested
list of f(i,j,...) applied thru the iterators.
Example: Table(f,[1,3,1],[2,6,2]) returns [f(3),f(5),f(7),f(9)]'''

it is slightly shortcut from the full form in that it doesn't allow
short cut conveniences. For example, one should be able to write
Table(f,[i,4], [j,1,9,2])
for
Table(f,[i,1,4,1], [j,1,9,2])

anyhow, for simplicity, let's start with this simpler spec.

I started to code this problem but this is quite a large problem, so i
figured it'd be fruitful to discuss it as we go.

The first problem i noted is that in Python, one cannot assign elements
in arrays where it doesn't exist yet. i.e.
a[7]=2
is illegal. This is in contrast to Perl, where one can do:
$a[3][7][2]=4
and automatically have a 3-dimentional nested array, where other
members simply have undefined values.

(This behavior of Perl is convenient when needed, but i recall in 2001
i spend the whole half a day trying to debug a program and it turned
out is caused by this behavior.)

With perl, a solution is to have Table simply generate the following
text and eval it.
--------------
my ($i,$j,$k,);
my @resultArray;

foreach $i (0 .. scalar(@{$ref_rangeSequence->[0]}) -1 ) {
foreach $j (0 .. scalar(@{$ref_rangeSequence->[1]}) -1 ) {
foreach $k (0 .. scalar(@{$ref_rangeSequence->[2]}) -1 ) {
$resultArray[$i][$j][$k] = &{Function(·@parameterList,$exprString)}
($ref_rangeSequence->[0]->[$i],$ref_rangeSequence->[1]->[$j],$ref_rangeSequence->[2]->[$k],);

};};};

return ·@resultArray;
------------
(in the above code, note the line $resultArray[$i][$j][$k]=...)

Another issue noted is that the so-called “list comprehension”
syntax construction in Python actually also contained a semantic
irregularity. That is to say, when the loops are nested inside a
list-comprehension, it still produced a flat list, instead of a nested
list.

This is quite a pain. I didn't realize this until i completed my code
and realized the result is a flat list. Here's the "wrong" code as a
result:

def Table2(fun, *itrs):
    dim=len (itrs)
    dummies = ['i'+repr(i) for i in Range(0,dim-1)]
    ll = [ (dummies[i],itrs[i][0],itrs[i][1],itrs[i][2]) for i in
Range(0,dim-1)]
    funString='f('
    for i in dummies: funString += i + ','
    funString = funString[0:len(funString)-1]
    funString += ')'
    loopStr= '[ ' + funString
    for i in range(0,dim):
        loopStr += ' for ' + dummies[i] + ' in Range(' +
repr(itrs[i][0])+','+repr(itrs[i][1])+','+repr(itrs[i][2]) + ') '
    loopStr += ' ]'
    print loopStr
    return eval(loopStr)

I was happy thinking that i'm done until am really dismayed by a
realization of this semantic irregulary. Both syntax irregularity and
semantic irregularity are ubiquitous in imperative languages.

So, now i have two choices:

(1) add another code to make a structure out of a flat list.
e.g. turn [1,2,3,4,5,6] to [[[1,2]],[[3,4]],[[5,6]]]

(2) rewrite the Table function to not use list comprehension. Instead,
use for loops.

I started to do (1) by writing a separate Partition function... bun in
the process i think perhaps (2) is better...

----------------
References:

• for a context of this message, see: http://xahlee.org/tree/tree.htm

• for a exposition of syntax aspects of irregularity of Python's
“list-comprehension”, see
http://xahlee.org/perl-python/list_comprehension.html

 Xah
 ···@xahlee.org
∑ http://xahlee.org/
From: Xah Lee
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <1119357263.288169.222100@f14g2000cwb.googlegroups.com>
the example in the spec of previous post is wrong. Here's corrected
version:

here's the Python spec for the Table function:

'''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the
range range(iStart,iEnd,iStep).  Example: Table(f,[3,10,2]) returns
[f(3),f(5),f(7),f(9)] Table(f,[iStart,iEnd,iStep],
[jStart,jEnd,jStep], ...) returns a nested list of f(i,j,...) applied
thru the iterators.  Example: Table(f,[1,3,1],[2,6,2]) returns
[[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]'''


it is slightly shortcut from the full form in that it doesn't allow
short cut conveniences. For example, one should be able to write
Table(f,[4], [1,9,2]) for Table(f,[1,4,1], [1,9,2])

Also, the first argument of expression has changed to a function
instead. Expression is much more convenient, but in languages that
isn't symbols oriented, a function is more appropriate.

anyhow, for simplicity, let's start with this simpler spec...

 Xah
 ···@xahlee.org
∑ http://xahlee.org/
From: Xah Lee
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <1119389957.552198.126070@o13g2000cwo.googlegroups.com>
sorry, another error. The example should be:

Table(f,[1,2,1],[2,6,2]) returns
[[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]


 Xah
 ···@xahlee.org
∑ http://xahlee.org/
From: Jerzy Karczmarczuk
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <792aed124e865c1c0666b7d3011b09f0.122484@mygate.mailgate.org>
Xah Lee, sending this to several innocent newsgroups:

> sorry, another error. The example should be:
> 
> Table(f,[1,2,1],[2,6,2]) returns
> [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]


Would it be too much, to ask you WHAT DO YOU WANT?
What is all this rubbish about?

Jerzy Karczmarczuk 



-- 
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
From: J�rgen Exner
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <8U1ue.2845$Uj.928@trnddc08>
Jerzy Karczmarczuk wrote:
> Xah Lee, sending this to several innocent newsgroups:
>
>> sorry, another error. The example should be:
>>
>> Table(f,[1,2,1],[2,6,2]) returns
>> [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]
>
>
> Would it be too much, to ask you WHAT DO YOU WANT?
> What is all this rubbish about?

Well, just ignore him. Xah is very well known as the current resident troll 
in CLPM (he replaced Godzilla, who hasn't been heard from for a while).

jue 
From: John Bokma
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <Xns967CD7D1EF78Acastleamber@130.133.1.4>
"J�rgen Exner" <········@hotmail.com> wrote:

> Well, just ignore him. Xah is very well known as the current resident
> troll in CLPM (he replaced Godzilla, who hasn't been heard from for a
> while). 

PurlGurl had a point now and then. I hope she's ok though.

-- 
John                   Small Perl scripts: http://johnbokma.com/perl/
               Perl programmer available:     http://castleamber.com/
            Happy Customers: http://castleamber.com/testimonials.html
                        
From: David Hopwood
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <vf2ue.44754$Vj3.9125@fe2.news.blueyonder.co.uk>
[c.l.perl.misc removed from Newsgroups]

Xah Lee wrote:
> Another issue noted is that the so-called “list comprehension”
> syntax construction in Python actually also contained a semantic
> irregularity. That is to say, when the loops are nested inside a
> list-comprehension, it still produced a flat list, instead of a nested
> list.

That's consistent with the behaviour of list comprehensions in other
languages -- including "set/tuple formers" in SETL
<http://www.cs.nyu.edu/~bacon/setl-doc.html>, which I believe was the
first language to support them. I don't know of any language where
a list comprehension with multiple loops creates nested lists.

-- 
David Hopwood <····················@blueyonder.co.uk>
From: d'yeux le pair
Subject: Re: tree functions daily exercise: Table
Date: 
Message-ID: <42c17e12$1_3@news.bluewin.ch>
David Hopwood a écrit :
> [c.l.perl.misc removed from Newsgroups]
> 
> Xah Lee wrote:
> 
>> Another issue noted is that the so-called “list comprehension”
>> syntax construction in Python actually also contained a semantic
>> irregularity. That is to say, when the loops are nested inside a
>> list-comprehension, it still produced a flat list, instead of a nested
>> list.
> 
> 
> That's consistent with the behaviour of list comprehensions in other
> languages -- including "set/tuple formers" in SETL
> <http://www.cs.nyu.edu/~bacon/setl-doc.html>, which I believe was the
> first language to support them. I don't know of any language where
> a list comprehension with multiple loops creates nested lists.
> 

PythonWin 2.3.3 (...)

 >>> [ [j for j in range(k)] for k in range(3)]
[[], [0], [0, 1]]

How were we supposed to understand that's not what you meant ?