473,394 Members | 1,841 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Duck typing alows true polymorfisim

lets say you want a generic numerical algorithom like sum

Ruby

def sum lst
lst.inject(0){|total,current| total*current}
end

Java // i dont know if there is a numeric super class for numbers

class Sum{
public static int sum(int[] lst){
int total = 0;
for(int current : lst){
total+=current;
}
return total;
}
// repeat for all other number types
}

Aug 25 '06 #1
15 1845
at*******@aol.com wrote:
lets say you want a generic numerical algorithom like sum

Ruby

def sum lst
lst.inject(0){|total,current| total*current}
end

Java // i dont know if there is a numeric super class for numbers

class Sum{
public static int sum(int[] lst){
int total = 0;
for(int current : lst){
total+=current;
}
return total;
}
// repeat for all other number types
}
What's your question? (Or, if no question, point?) :-)

Totally off topic (and indeed "off-list"..) is that really how ruby
sums a list? How does that work? Doesn't the '*' mean multiply? and
what are the pipe symbols for? (Feel free to ignore these questions. I
should really go look it up myself if I'm so curious..)

Peace,
~Simon

Aug 25 '06 #2
at*******@aol.com wrote:
lets say you want a generic numerical algorithom like sum
Hmmm, I thought you were going to announce that you were the first born
son of Xah Lee. Actually you did!

--
John MexIT: http://johnbokma.com/mexit/
personal page: http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
Aug 25 '06 #3

at*******@aol.com wrote:
lets say you want a generic numerical algorithom like sum

Ruby

def sum lst
lst.inject(0){|total,current| total*current}
end

Java // i dont know if there is a numeric super class for numbers

class Sum{
public static int sum(int[] lst){
int total = 0;
for(int current : lst){
total+=current;
}
return total;
}
// repeat for all other number types
}

Any more to add? Your question is not exactly clear. Are you asking how
to do higher order procedures in Python? Here's sum as a higher-order
procedure... It sums the numbers from a to b (or any thing that can be
compared and added with "<" and "+").

def Sum(term, next, a, b):
if(a b):
return 0
else:
return (term(a) + (Sum(term, next, next(a), b)

This function takes two functions (term and next) and two objects (in
our case numbers) representing the range to sum across. Now let's say
you want to add the numbers 1 through 10. The term for the summation
would just be the number, so the term function would simply be a
function called identity, and could be defined as

def identity(x):
return x

To get the next term, we are just adding one each time (i.e. 1, 2, 3,
4, ...). So our next function is

def increment(x):
return x += 1

Then we call Sum(identity, increment, 1, 10), and we get 1 + 2 + 3 + 4
+ and so on.

Now what if you wanted the sum of the CUBES of 1 through 10? Easy, we
replace the term function with a function cube(x) that returns x*x*x.

Sum(cube,increment,1,10)

Hence each term in our summation is the cube, but we are still
incrementing by one each time, so we get (1^3 + 2^3 + 3^3 + 4^3 + ...)

Similarly we can change the next function to skip certain number, meet
certain requirement, do some tranformation, whatever. The fact that
python accept and uses functions as parameters to other functions is
awesome in terms of power, but it can get a little mind boggling
sometimes.

Aug 25 '06 #4
What was i thinkinng repace * with + i was'nt thinking i origanaly
thaught of sum of squares so i put a * insted of a +

Aug 25 '06 #5
at*******@aol.com wrote:
What was i thinkinng repace * with + i was'nt thinking i origanaly
thaught of sum of squares so i put a * insted of a +
But again, what's your question?

Aug 25 '06 #6

"David Ells" <el********@gmail.comwrote in message
news:11*********************@m73g2000cwd.googlegro ups.com...
def increment(x):
return x += 1
'return x+1' works better ;-)

tjr

Aug 25 '06 #7
In comp.lang.java.advocacy, at*******@aol.com
<at*******@aol.com>
wrote
on 25 Aug 2006 12:05:21 -0700
<11*********************@i3g2000cwc.googlegroups.c om>:
lets say you want a generic numerical algorithom like sum

Ruby

def sum lst
lst.inject(0){|total,current| total*current}
end

Java // i dont know if there is a numeric super class for numbers

class Sum{
public static int sum(int[] lst){
int total = 0;
for(int current : lst){
total+=current;
}
return total;
}
// repeat for all other number types
}
There isn't; Java makes the distinction between an int and
an Integer, a double and a Double. Java 5 did introduce
autoboxing, which makes things like

Number[] numbers = new Number[]{1, 2.3, 4, 5.6};

possible, and Number is a baseclass for both Integer and
Double (but not int and double).

Therefore, one could write:

public class Sum {
public static double sum(int[] lst)
{
Number[] nlst = new Number[lst.length];
for(int i = 0; i < nlst.length; i++) nlst[i] = new Integer(lst[i]);
return sum(Arrays.asList(nlst));
}
public static double sum(double[] lst)
{
Number[] nlst = new Number[lst.length];
for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]);
return sum(Arrays.asList(nlst));
}
public static double sum(float[] lst)
{
Number[] nlst = new Number[lst.length];
for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]);
return sum(Arrays.asList(nlst));
}
public static double sum(Number[] lst)
{
return sum(Arrays.asList(lst));
}
public static double sum(Collection<Numberlst)
{
double sum = 0;
for(Iterator<Numberi = lst.iterator(); i.hasNext())
sum += i.next().doubleValue();
return sum;
}

}

A rather ugly but possibly useful duckling.

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
Aug 25 '06 #8
<at*******@aol.comwrote in message
news:11*********************@i3g2000cwc.googlegrou ps.com...
lets say you want a generic numerical algorithom like sum

Ruby

def sum lst
lst.inject(0){|total,current| total*current}
end

Java // i dont know if there is a numeric super class for numbers
[snip- int only example]

There is, and it is interesting because it hilights the
real difference: Java uses C style numerics, where
you select the model of arithmetic you want using
the type system. Here's a 'generic sum' for Java:

public static double sum(Iterable<? extends Numberlist)
{
double total=0;
for(Number n : list)
double+=n.doubleValue();
return total;
}

If I got it right (I'm a bit rusty with Java) that will sum
any collection containing any kind of number.

But you have to specify that you want *double* arithmetic,
as you see; had I chosen int, it would produce different
answers.

In some languages- like Ruby I think- you cannot make
this choice. Your language chooses for you. Most languages
that do this prefer accuracy to speed, so everything gets
promoted to larger types on demand, and things like
rounding and overflow are avoided.

However, even if you agree with this choice, you can
still get into trouble. Promoting to 'double' or 'float'
imposes different errors that you'd get with ints, but
they still exist. Sometimes a ratio type is better; other
times you would prefer a decimal type.

The greatest advantage of static type systems is to
expose design decisions like these in a way the
compiler can see.
Aug 26 '06 #9

Terry Reedy wrote:
"David Ells" <el********@gmail.comwrote in message
news:11*********************@m73g2000cwd.googlegro ups.com...
def increment(x):
return x += 1

'return x+1' works better ;-)

tjr
Heh, woops... thanks

Aug 26 '06 #10

"Simon Forman" <ro*********@yahoo.comwrote in message
news:11*********************@i42g2000cwa.googlegro ups.com...
at*******@aol.com wrote:
>lets say you want a generic numerical algorithom like sum
What's your question? (Or, if no question, point?) :-)
Reads like the weekly "Ruby is better than Java because XXXXX" post.
Aug 30 '06 #11
In comp.lang.java.advocacy, Jeroen Wenting
<jwenting>
wrote
on Wed, 30 Aug 2006 20:18:52 +0200
<12*************@corp.supernews.com>:
>
"Simon Forman" <ro*********@yahoo.comwrote in message
news:11*********************@i42g2000cwa.googlegro ups.com...
>at*******@aol.com wrote:
>>lets say you want a generic numerical algorithom like sum
>What's your question? (Or, if no question, point?) :-)
Reads like the weekly "Ruby is better than Java because XXXXX" post.
Well, FWIW one could throw this into the pot and watch it explode:

http://www.approximity.com/ruby/Comp...st_m_java.html

:-)

This table needs some work. The leftmost column is
unidentified, for example ("Capability" or "Feature"
suggests itself here) and each of these capabilities or
features should probably have a link to a short description
of the capability or feature, preferably with an example.

Also, one language is very conspicuous by its absence: C#.
One could also add C, Basic, and ISO Pascal; the first is
widely used but lacks polymorphism, inheritance, dynamic
casting, etc., and the last is probably not used anywhere
in its form (though dialects are plenty), since one can't
do anything *with* it, really -- though IIRC someone has
told me it can at least open an arbitrary file now, as
opposed to having the user pass one down in the program
identifier list. :-)

As for the middle one: which dialect? Was it ever
standardized? Visual Basic is a very object-oriented
language in spots, but it's not the only variant; I
used to use at least 4 other variants off and on:

GWBasic -- old IBM PCs
ABasic -- Amiga variant
AmigaBasic -- Microsoft-sponsored Amiga variant
HP Basic (?) -- load tape into very old HP 21xx-series
computer and one had a multitasking Basic which could
do the simpler stuff, but its error diagnostics were
pure numeric: ERROR 67 IN LINE 20. Fortunately, we
had plenty of pamphlets detailing the errors.

Also, Java now has templates. (The implementation is
pretty gross and has some quirks, IMO, but it's better
than nothing.) C++ has a typing system ("type_of" or
some such; I'd have to look) which yields little
more than the mangled type name and static inheritance
testing capabilities. Of course C++ doesn't have
dynamic inheritance anyway.

One could include additional capabilities:

Dynamic type creation. I don't know if Java has this or not.
One can of course attempt bytecode synthesis -- I think that's
what BCEL uses -- but that's a bit of a hack.

Dynamic method creation. Java does *not* have this. AIUI
Smalltalk-80 does; one can take an existing class and add
methods thereto.

Dynamic method override. This may be an artificial distinction
but in some languages -- Smalltalk-80 again, presumably -- one
can take an existing method implementation and override it in
the same class, but without allowing the creation of new methods.
How this would be enforced without additional keywords and/or
a full-fledged ACL method/metadata system, I for one do not know.

Dynamic method deletion. I for one might only want this in
the context of a "sandbox" but if one can create methods,
one should be able to delete them as well if only because
of undo.

Dynamic method rename. This could lead to much madness
but this might be useful during sandboxing.

Dynamic method signature changing. Eclipse has a
reasonable way of doing it using source but I'll admit to
wondering whether it makes sense given a Method descriptor
whether one should be able to edit (as opposed to viewing
or invoking) that descriptor, and when. One might implement
this as a new method, followed by a delete of the old one.

Dynamic other method deletion. If one can delete one's own
methods in an edit session, should it be possible to delete
others' methods too? An interesting question.

Dynamic inheritance. For those languages that support
inheritance one might liken it to changing what the
language inherits or implements on the fly. I don't
know of any language apart from Smalltalk that can even
think about allowing dynamic inheritance, but it's a thought.

Operator overload (e.g., C++'s operator ==()).

Name overload. C does not have it; C++ and Java do. I suspect
Ruby and Python do as well.

Globals. Java has no globals as such, unless one counts
class names. C is all globals, unless one counts statics.

Unnamed classes. new Runnable() { public void run() {...} }
is Java's contribution. Can be useful.

Nested classes.

Primitive types -- in other words, the int<->Integer
dichotomy we all know and love in Java; such also exists
in C++ and IINM C#. I'm not sure if Smalltalk has such
a concept, or not; Smalltalk allows overrides on numbers.
(In Java one might contemplate 2.toString(), for example!)

Arbitrary integer size. The only language I know having this
is Common LISP.

Explicit module-level identifier scoping. In C++ this
might be implemented during link using the -E flag on ld,
for example (there is the Microsoft concept of exporting
in their DLLs, which is vaguely similar as well).
An identifier could be "global" in the module but
inaccessible to those outside of the module. Modules
can include other modules in C++, which makes life
even more interesting. (This might be more of an
environmental versus a language issue.)

Thread-level variable/value scoping. In Java this is done
using the ThreadLocal class, but is not (AFAICT) supported
by the language proper. This of course differs from
call-level (stack), global-level, and class-level scoping.
One might even contemplate function-level scoping, but
that would only be useful if one can create new functions
on the fly and modify these values; otherwise, they might
as well be static.

Persistability. In Java one can implement Serializable
or Externalizable, and generate output from an object.
I've always considered this a bit of a weird hack but it
can come in handy, and forms one leg of the Java EJB
implementation.

Transient field. In Java a capability exists to mark a
field as transient, which is a hint during serialization
that this field in a class not be persisted. (One can
check for this using the Modifier.TRANSIENT bit.)

Volatile field. In Java there is a volatile keyword. I
don't know its precise semantics but it applies to fields.

Virtuals. In C++ one must explicitly declare a function
virtual; C has none at all, and in Java one must explicitly
declare a function final (disallowing overrides) and cannot
really disable a non-method's "virtuality" at all.

Pure/abstract virtuals. C++ has the "=0" construct; Java
has the abstract keyword.

Static virtuals.

Delegates. This Microsoftish concept is a bit hard for me
to pin down (it feels a lot like a C++ method pointer --
or even a C function pointer) but is occasionally touted
as an advantage for such languages as C++ and the ill-fated
Java++, which had them as part of the language.

First-level object functions. AIUI, this is a high-level
concept which would allow for constructs in a hypothetical
language such as

k = (f @ g)(s1,s2,s3);

if f has arguments (int v) and g has arguments (string s1, string s2,
string s3). It would also allow for constructs such as

h = f @ g;

where h is a "function variable" of some sort -- and it would have
the same signature as g. (The '@' is used in lieu of 'o', although
one might use character U+2218 (ring operator) in a theoretical
language where everyone understands Unicode.)

C#'s event handling emulates this concept to some extent
using the += operator, though I doubt they do it all that
generally -- or all that well.

Function-function operators. Under certain conditions the
construct f + g makes sense, if they have compatible signatures;
one might even write

int (f + g)(int a)
{
return f(a) + g(a)
}

Ditto for f - g, f * g, and even f += g if f returns a reference.
One can also contemplate unary operators such as '-f' .

Set/collection union/intersection/subtraction/element
of support. This is probably most useful for hard-core
mathematicians and database junkies. :-) In Java one
might declare a Union class easily enough, which takes
two collections and tries to do something intelligent with
them during a scan with the iterator, and of course
the .contains() method is good enough for now.

Integrated database access (and how tightly). C++ has
none at all, though of one can use various third-party
libraries. Java has some base-level API -- the java.sql.*
and javax.sql* library. I suspect C#'s access is similar;
I don't know regarding Ruby. A variant of COBOL was
able to access the database -- DEC's DBMS product,
which was a CODASIL affair -- by using statements in
the language itself. Nowadays, apparently, such are
considered slightly problematic, mostly because DB defs
change a little too often.

Arbitrary iterator positioning. In C++ some collections
can position an iterator in an arbitrary location within
the collection -- the only obvious one would be arrays.
The closest one might get in current Java is to do a
head(), tail(), or subset() and iterate over that.

GUI support -- this is primarily API/library but might
be put in the language if it makes sense -- perhaps when
combined with collections and sets (e.g., is a point
within a rectangle?), though there are some issues such
as whether one would want to enumerate all the elements
in a collection (points in a rectangle).

There's probably a number I've missed but there are
some interesting and somewhat unexplored directions in Java.
Whether it makes sense to explore them is not clear to me.

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
Aug 30 '06 #12
The Ghost In The Machine <ew***@sirius.tg00suus7038.netwrites:
Also, one language is very conspicuous by its absence: C#.
He does not date any of the updates, so it's unclear how recently it
has been updated (a lot of the web is stale, like a rotting tree in a
forest.)
AmigaBasic -- Microsoft-sponsored Amiga variant
Well, at the time Microsoft were the makers of the de-facto BASIC
implementations - M-BASIC for CP/M, the various variants in VC-20 and
C-64 and later derivates of those, and many other home computers.
"Sponsored" should probably be "created" instead - I assume they were
paid for the job.
Also, Java now has templates. (The implementation is pretty gross
and has some quirks, IMO, but it's better than nothing.) C++ has a
typing system ("type_of" or some such; I'd have to look) which
yields little more than the mangled type name and static inheritance
testing capabilities. Of course C++ doesn't have dynamic inheritance
anyway.
There's the virtual stuff, and you could conceivably implement dynamic
inheritance via the bare-bones C layer - like function pointers. The
type information in C++ (RTTI) is optional.
Dynamic type creation. I don't know if Java has this or not. One can
of course attempt bytecode synthesis -- I think that's what BCEL
uses -- but that's a bit of a hack.
Groovy could possibly be used for that; also IIRC Java 6 adds some
features for that. I seem to recall security implications being one
reason this ability wasn't included from the start.
Dynamic method creation. Java does *not* have this. AIUI
Smalltalk-80 does; one can take an existing class and add methods
thereto.
Yes, but that's because a Smalltalk program lives inside a big binary
"image" that is mutable. Woe unto you if that big binary file gets
corrupted.
Dynamic method deletion. I for one might only want this in the
context of a "sandbox" but if one can create methods, one should be
able to delete them as well if only because of undo.
The problem with deleting a method is whether the runtime can handle
it: Smalltalk has doesNotUnderstand:#aMessage, Java has
NoSuchMetohdError - what does C++ do? A zeroed virtual method would
cause a pure virtual method call error, which I guess C++ programmers
are trained to take into account. Also, if class A has a method and
you delet it in subclass B, it breaks the Liskov Substitution
Principle, there B should be able to function where an A is wanted.
Dynamic method rename. This could lead to much madness but this
might be useful during sandboxing.
A method's name and its "address" are distinct, but for dynamic method
dispatch, what about any other code that doesn't know the new name but
assumes the method is called the same?
Dynamic inheritance. For those languages that support inheritance
one might liken it to changing what the language inherits or
implements on the fly. I don't know of any language apart from
Smalltalk that can even think about allowing dynamic inheritance,
but it's a thought.
If you can change a Perl class, er, module's @INC array I think that
would support it.
Operator overload (e.g., C++'s operator ==()).
Or rather "dotless/prefix method invocation with the added baggage of
precedence rules". Smalltalk solves this by 1) not having those
precedence rules, 2) have dotless method invocation and 3)
>
Name overload. C does not have it; C++ and Java do. I suspect Ruby
and Python do as well.
Are you referring to namespaces, ie. namespace isolation?
Globals. Java has no globals as such, unless one counts class names.
C is all globals, unless one counts statics.
Even the fully qualified classes are only "global" in the context of a
classloader and whatever classloaders it delegates to.
Unnamed classes. new Runnable() { public void run() {...} } is
Java's contribution. Can be useful.
Well, they do end up with a name after compilation. And you do not
want to open that can of worms since then you end up with Ruby and
Smalltalk users dragging out closures and C# and Lisp users dragging
out lambdas... :)
Nested classes.
Generally that's just a namespace issue. In Java, a class Fie nested
inside Foo is the top-level class Foo$Fie with some compiler magic to
ensure it's used correctly, which leads to funny stuff like

Foo.Fie object = new Foo().new Fie();

which gets turned into the bytecode equivalent of

Foo$Fie object = new Foo$Fie(new Foo());
Primitive types -- in other words, the int<->Integer dichotomy we
all know and love in Java; such also exists in C++ and IINM C#. I'm
not sure if Smalltalk has such a concept, or not; Smalltalk allows
overrides on numbers. (In Java one might contemplate 2.toString(),
for example!)
In Smalltalk you ask the 1 object to count to 10 for a loop. It makes
sense there, it would not feel "right" in the C family...
Arbitrary integer size. The only language I know having this is
Common LISP.
java.math.BigInteger, but the operations you can perform are limited.
Thread-level variable/value scoping. In Java this is done using the
ThreadLocal class, but is not (AFAICT) supported by the language
proper.
Yes, and that leads to a problem where if you forget to null a
ThreadLocal you can "leak" objects.
One might even contemplate function-level scoping, but that would
only be useful if one can create new functions on the fly and modify
these values; otherwise, they might as well be static.
As long as you make sure you never use a private static member
elsewhere than in that particular method, it can play the role of a
function-level method.
Persistability. In Java one can implement Serializable or
Externalizable, and generate output from an object. I've always
considered this a bit of a weird hack but it can come in handy, and
forms one leg of the Java EJB implementation.
Persistability is left as an excercise to libraries in most languages.
Volatile field. In Java there is a volatile keyword. I don't know
its precise semantics but it applies to fields.
In Java it's generally a hint to the optimizer NOT to optimize away or
make any assumptions about access to a field.
C#'s event handling emulates this concept to some extent using the
+= operator, though I doubt they do it all that generally -- or all
that well.
Well it's closer to a list of function pointers, sorry delegates; not
much more than Java's more explicit (or cumbersome if you like) event
interfaces can do.
Integrated database access (and how tightly). C++ has none at all,
though of one can use various third-party libraries. Java has some
base-level API -- the java.sql.* and javax.sql* library.
Well, those are general library APIs that require native or
socket-based implementation by vendors or third parties.

What you talk about is better represented by "inline" SQL in the form
of SQLJ or Oracle's Pro*C and related products.

It boils down to how much should be in the language (syntax, compiler,
runtime) and how much should be left to libraries. E.g. he has a "no"
for garbage collection in C++, but there are libraries for that sort
of thing (relying mostly on the ability to override the new, delete
and assignment operators. Even in Java you often have a choice of
garbage collector algorithms in a runtime.
Aug 31 '06 #13
In comp.lang.java.advocacy, Tor Iver Wilhelmsen
<ja********@hotmail.com>
wrote
on 31 Aug 2006 18:31:15 +0200
<uz***********@hotmail.com>:
The Ghost In The Machine <ew***@sirius.tg00suus7038.netwrites:
>Also, one language is very conspicuous by its absence: C#.

He does not date any of the updates, so it's unclear how recently it
has been updated (a lot of the web is stale, like a rotting tree in a
forest.)
Aye; my webpage has a similar problem. :-)
>
>AmigaBasic -- Microsoft-sponsored Amiga variant

Well, at the time Microsoft were the makers of the de-facto BASIC
implementations - M-BASIC for CP/M, the various variants in VC-20 and
C-64 and later derivates of those, and many other home computers.
"Sponsored" should probably be "created" instead - I assume they were
paid for the job.
OK, "created" then. :-)

>
>Also, Java now has templates. (The implementation is pretty gross
and has some quirks, IMO, but it's better than nothing.) C++ has a
typing system ("type_of" or some such; I'd have to look) which
yields little more than the mangled type name and static inheritance
testing capabilities. Of course C++ doesn't have dynamic inheritance
anyway.

There's the virtual stuff, and you could conceivably implement dynamic
inheritance via the bare-bones C layer - like function pointers. The
type information in C++ (RTTI) is optional.
Oh yeah, that's true. Still not all that dynamic, though, unless
one recompiles.
>
>Dynamic type creation. I don't know if Java has this or not. One can
of course attempt bytecode synthesis -- I think that's what BCEL
uses -- but that's a bit of a hack.

Groovy could possibly be used for that; also IIRC Java 6 adds some
features for that. I seem to recall security implications being one
reason this ability wasn't included from the start.
Not familiar with Groovy; I'll have to look into that.
It's amazing what's out there; one of the problems with
Free Open Source Software (FOSS) is that there's multiple
choices for the obvious stuff. :-)
>
>Dynamic method creation. Java does *not* have this. AIUI
Smalltalk-80 does; one can take an existing class and add methods
thereto.

Yes, but that's because a Smalltalk program lives inside a big binary
"image" that is mutable. Woe unto you if that big binary file gets
corrupted.
Indeed.

I for one would want Smalltalk to have the ability to
transcript certain messages but would have to look.
(One might call that an edit audit trail.)
>
>Dynamic method deletion. I for one might only want this in the
context of a "sandbox" but if one can create methods, one should be
able to delete them as well if only because of undo.

The problem with deleting a method is whether the runtime can handle
it: Smalltalk has doesNotUnderstand:#aMessage, Java has
NoSuchMetohdError - what does C++ do? A zeroed virtual method would
cause a pure virtual method call error, which I guess C++ programmers
are trained to take into account.
I'd frankly have to look. My thinking is that it's a message followed
by an exit().
Also, if class A has a method and
you delet it in subclass B, it breaks the Liskov Substitution
Principle, there B should be able to function where an A is wanted.
Heh...an interesting name; I'm not familiar with that
issue. Of course it's important for B to be an A in
many cases, though AFAICT usually what happens is that
A declares a method virtual with an implementation and B
munges it.
>
>Dynamic method rename. This could lead to much madness but this
might be useful during sandboxing.

A method's name and its "address" are distinct, but for dynamic method
dispatch, what about any other code that doesn't know the new name but
assumes the method is called the same?
What indeed? Much madness.
>
>Dynamic inheritance. For those languages that support inheritance
one might liken it to changing what the language inherits or
implements on the fly. I don't know of any language apart from
Smalltalk that can even think about allowing dynamic inheritance,
but it's a thought.

If you can change a Perl class, er, module's @INC array I think that
would support it.
>Operator overload (e.g., C++'s operator ==()).

Or rather "dotless/prefix method invocation with the added baggage of
precedence rules". Smalltalk solves this by 1) not having those
precedence rules, 2) have dotless method invocation and 3)
....?

I'll admit Smalltalk has a lot of things, but popularity isn't
unfortunately one of them. :-/
>
>>
Name overload. C does not have it; C++ and Java do. I suspect Ruby
and Python do as well.

Are you referring to namespaces, ie. namespace isolation?
Hmm...that could use clarification. The general idea is that
Java and C++ allow

void routine1(const char *);
void routine1(int);
void routine1(double);

in the same module or class.

I suppose a slightly better term would be "function overloading", since
that's what it was called some time back.

C does not have this capability, and it occasionally leads to problems
if a program doesn't use proper design methods (such as declaring all
methods in .h files and including them, as opposed to putting local
extern signatures in the .C code -- yes, my prior employer had code
that did exactly that for awhile; hopefully it's cleaned up by now since
it's been almost 6 years :-) ).
>
>Globals. Java has no globals as such, unless one counts class names.
C is all globals, unless one counts statics.

Even the fully qualified classes are only "global" in the context of a
classloader and whatever classloaders it delegates to.
Good point.
>
>Unnamed classes. new Runnable() { public void run() {...} } is
Java's contribution. Can be useful.

Well, they do end up with a name after compilation.
Picky, picky. :-) In any event the name is not available
to the program source; one can't expect to do things like

Runnable$1 r = new Runnable() { public void run() {...} }

and hope for it to work. One might be able to do something
slightly silly like

Class c = Class.forName("Runnable$1");

c.newInstance();

but for Java that's slightly problematic, especially if there's
more than one Runnable in that class.
And you do not
want to open that can of worms since then you end up with Ruby and
Smalltalk users dragging out closures and C# and Lisp users dragging
out lambdas... :)
Yes, well AFAICT a closure is some code with a little context; in Java
some of the context is required to have final variables, or a method by
which it can pick up its owning class's members or call its routines.
>
>Nested classes.

Generally that's just a namespace issue. In Java, a class Fie nested
inside Foo is the top-level class Foo$Fie with some compiler magic to
ensure it's used correctly, which leads to funny stuff like

Foo.Fie object = new Foo().new Fie();

which gets turned into the bytecode equivalent of

Foo$Fie object = new Foo$Fie(new Foo());
Hm.
>
>Primitive types -- in other words, the int<->Integer dichotomy we
all know and love in Java; such also exists in C++ and IINM C#. I'm
not sure if Smalltalk has such a concept, or not; Smalltalk allows
overrides on numbers. (In Java one might contemplate 2.toString(),
for example!)

In Smalltalk you ask the 1 object to count to 10 for a loop. It makes
sense there, it would not feel "right" in the C family...
Or anywhere else that I know of offhand.
>
>Arbitrary integer size. The only language I know having this is
Common LISP.

java.math.BigInteger, but the operations you can perform are limited.
Hm. OK, "arbitrary number size with transparency".
>
>Thread-level variable/value scoping. In Java this is done using the
ThreadLocal class, but is not (AFAICT) supported by the language
proper.

Yes, and that leads to a problem where if you forget to null a
ThreadLocal you can "leak" objects.
Ugh.

Well, unfortunately for Java it's all too easy to
leak certain objects, though the only one coming to
mind are FileInputStream, FileOutputStream, FileReader,
and FileWriter. Forget to close them before the variable
goes out of scope and they remain open forever, as far as
I can tell.

(Maybe that'll be fixed in a subsequent rev. I don't know.)
>
>One might even contemplate function-level scoping, but that would
only be useful if one can create new functions on the fly and modify
these values; otherwise, they might as well be static.

As long as you make sure you never use a private static member
elsewhere than in that particular method, it can play the role of a
function-level method.
>Persistability. In Java one can implement Serializable or
Externalizable, and generate output from an object. I've always
considered this a bit of a weird hack but it can come in handy, and
forms one leg of the Java EJB implementation.

Persistability is left as an excercise to libraries in most languages.
True, and in that library one usually has a base class.
>
>Volatile field. In Java there is a volatile keyword. I don't know
its precise semantics but it applies to fields.

In Java it's generally a hint to the optimizer NOT to optimize away or
make any assumptions about access to a field.
>C#'s event handling emulates this concept to some extent using the
+= operator, though I doubt they do it all that generally -- or all
that well.

Well it's closer to a list of function pointers, sorry delegates; not
much more than Java's more explicit (or cumbersome if you like) event
interfaces can do.
Operator overloading has two issues: it's far more convenient to
write something like

Matrix m1, m2;

Matrix m3 = m1 * m2;

instead of

Matrix m3 = m1.multiplyBy(m2);

or

Matrix m3 = Matrix.multiply(m1, m2);

but it's harder for the compiler and the user to parse.
So it's a tradeoff.

The main problem I have with Swing event handling is
that occasionally it's not clear when I have to tell the
listeners that I've done something to a class which manages
a bunch of listeners. Also, ideally, one would not need
to fire off the listeners in sequence -- though without
explicitly spawning subthreads that would be difficult
in Java.

The main problem with C# event handling is that I don't
know its ramifications, but I consider delegates a bit silly,
mostly because of the Java++ fiasco. That was not COOL,
Microsoft. :-)
>
>Integrated database access (and how tightly). C++ has none at all,
though of one can use various third-party libraries. Java has some
base-level API -- the java.sql.* and javax.sql* library.

Well, those are general library APIs that require native or
socket-based implementation by vendors or third parties.

What you talk about is better represented by "inline" SQL in the form
of SQLJ or Oracle's Pro*C and related products.
There's the issue of how to handle schema changes, as well; that's
probably why nobody wants to tightly integrate anymore. I can't really
blame 'em.
>
It boils down to how much should be in the language (syntax, compiler,
runtime) and how much should be left to libraries. E.g. he has a "no"
for garbage collection in C++, but there are libraries for that sort
of thing (relying mostly on the ability to override the new, delete
and assignment operators. Even in Java you often have a choice of
garbage collector algorithms in a runtime.
Hm; I'll have to research that. Apart from the aforementioned stream
issues and the occasional "oops I left the thing in the global
Collection" issue, though, I've not had to do much with garbage
collection, though I did write a rather poorly-performing cache.

I will definitely have to fiddle with WeakReference at some point,
though it's probably easier just to punt to a solution like
Hibernate or JBossCache (TreeCache) or even Castor/JDO.

Like I said, FOSS has a lot of stuff out there; the main problem
for me is finding it. :-)

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
Aug 31 '06 #14
Just a quick note in the midst of this:

The Ghost In The Machine wrote:
Dynamic type creation. I don't know if Java has this or not.
One can of course attempt bytecode synthesis -- I think that's
what BCEL uses -- but that's a bit of a hack.
Since no one has pointed this out, I should mention the oft-neglected
class java.lang.reflect.Proxy, which allows you to create at runtime a
class that implements a given set of interfaces and a single instance
of that class. Methods are all handled in a manner similar to ruby's
method_missing - that is, a single method is passed the method (as a
Method object) and arguments (as Object[]).

Beanshell (http://www.beanshell.org/) uses this to allow dynamic,
scripted objects (created at runtime) to implement arbitrary Java
interfaces. Reportedly, this greatly simplifies swing and AWT
programming, since one can ignore methods that are specified as part of
the interface but aren't actually used through the course of the
program.

Aug 31 '06 #15
The Ghost In The Machine wrote:
In comp.lang.java.advocacy, Tor Iver Wilhelmsen
<ja********@hotmail.com>
wrote
on 31 Aug 2006 18:31:15 +0200
<uz***********@hotmail.com>:
The Ghost In The Machine <ew***@sirius.tg00suus7038.netwrites:
Also, one language is very conspicuous by its absence: C#.
He does not date any of the updates, so it's unclear how recently it
has been updated (a lot of the web is stale, like a rotting tree in a
forest.)

Aye; my webpage has a similar problem. :-)
AmigaBasic -- Microsoft-sponsored Amiga variant
Well, at the time Microsoft were the makers of the de-facto BASIC
implementations - M-BASIC for CP/M, the various variants in VC-20 and
C-64 and later derivates of those, and many other home computers.
"Sponsored" should probably be "created" instead - I assume they were
paid for the job.

OK, "created" then. :-)

Also, Java now has templates. (The implementation is pretty gross
and has some quirks, IMO, but it's better than nothing.) C++ has a
typing system ("type_of" or some such; I'd have to look) which
yields little more than the mangled type name and static inheritance
testing capabilities. Of course C++ doesn't have dynamic inheritance
anyway.
There's the virtual stuff, and you could conceivably implement dynamic
inheritance via the bare-bones C layer - like function pointers. The
type information in C++ (RTTI) is optional.

Oh yeah, that's true. Still not all that dynamic, though, unless
one recompiles.
Dynamic type creation. I don't know if Java has this or not. One can
of course attempt bytecode synthesis -- I think that's what BCEL
uses -- but that's a bit of a hack.
Groovy could possibly be used for that; also IIRC Java 6 adds some
features for that. I seem to recall security implications being one
reason this ability wasn't included from the start.

Not familiar with Groovy; I'll have to look into that.
It's amazing what's out there; one of the problems with
Free Open Source Software (FOSS) is that there's multiple
choices for the obvious stuff. :-)
Dynamic method creation. Java does *not* have this. AIUI
Smalltalk-80 does; one can take an existing class and add methods
thereto.
Yes, but that's because a Smalltalk program lives inside a big binary
"image" that is mutable. Woe unto you if that big binary file gets
corrupted.

Indeed.

I for one would want Smalltalk to have the ability to
transcript certain messages but would have to look.
(One might call that an edit audit trail.)
The comments "Woe unto you if that big binary file gets corrupted" are
plain wrong.

For at least 25 years (and perhaps back to Smalltalk-72?) Smalltalk
implementations have comprised an image file, a sources file, and a
change log. The change log records changes to objects, as Smalltalk
statements that can be replayed to reproduce those changes - and as
Smalltalk classes and methods are just objects, that means code changes
are recorded in the change log and can be reproduced even if the image
file is somehow corrupted.

By the late '80s, commercial Smalltalk development had adopted tightly
integrated, fine grained, multi-user version control - everytime a
method was compiled a new edition of the method was recorded in the
version control system, which really helps continuous integration
across the team.
>
Dynamic method deletion. I for one might only want this in the
context of a "sandbox" but if one can create methods, one should be
able to delete them as well if only because of undo.
The problem with deleting a method is whether the runtime can handle
it: Smalltalk has doesNotUnderstand:#aMessage, Java has
NoSuchMetohdError - what does C++ do? A zeroed virtual method would
cause a pure virtual method call error, which I guess C++ programmers
are trained to take into account.

I'd frankly have to look. My thinking is that it's a message followed
by an exit().
Also, if class A has a method and
you delet it in subclass B, it breaks the Liskov Substitution
Principle, there B should be able to function where an A is wanted.

Heh...an interesting name; I'm not familiar with that
issue. Of course it's important for B to be an A in
many cases, though AFAICT usually what happens is that
A declares a method virtual with an implementation and B
munges it.
Dynamic method rename. This could lead to much madness but this
might be useful during sandboxing.
A method's name and its "address" are distinct, but for dynamic method
dispatch, what about any other code that doesn't know the new name but
assumes the method is called the same?

What indeed? Much madness.
Dynamic inheritance. For those languages that support inheritance
one might liken it to changing what the language inherits or
implements on the fly. I don't know of any language apart from
Smalltalk that can even think about allowing dynamic inheritance,
but it's a thought.
If you can change a Perl class, er, module's @INC array I think that
would support it.
Operator overload (e.g., C++'s operator ==()).
Or rather "dotless/prefix method invocation with the added baggage of
precedence rules". Smalltalk solves this by 1) not having those
precedence rules, 2) have dotless method invocation and 3)

...?

I'll admit Smalltalk has a lot of things, but popularity isn't
unfortunately one of them. :-/
>
Name overload. C does not have it; C++ and Java do. I suspect Ruby
and Python do as well.
Are you referring to namespaces, ie. namespace isolation?

Hmm...that could use clarification. The general idea is that
Java and C++ allow

void routine1(const char *);
void routine1(int);
void routine1(double);

in the same module or class.

I suppose a slightly better term would be "function overloading", since
that's what it was called some time back.

C does not have this capability, and it occasionally leads to problems
if a program doesn't use proper design methods (such as declaring all
methods in .h files and including them, as opposed to putting local
extern signatures in the .C code -- yes, my prior employer had code
that did exactly that for awhile; hopefully it's cleaned up by now since
it's been almost 6 years :-) ).
Globals. Java has no globals as such, unless one counts class names.
C is all globals, unless one counts statics.
Even the fully qualified classes are only "global" in the context of a
classloader and whatever classloaders it delegates to.

Good point.
Unnamed classes. new Runnable() { public void run() {...} } is
Java's contribution. Can be useful.
Well, they do end up with a name after compilation.

Picky, picky. :-) In any event the name is not available
to the program source; one can't expect to do things like

Runnable$1 r = new Runnable() { public void run() {...} }

and hope for it to work. One might be able to do something
slightly silly like

Class c = Class.forName("Runnable$1");

c.newInstance();

but for Java that's slightly problematic, especially if there's
more than one Runnable in that class.
And you do not
want to open that can of worms since then you end up with Ruby and
Smalltalk users dragging out closures and C# and Lisp users dragging
out lambdas... :)

Yes, well AFAICT a closure is some code with a little context; in Java
some of the context is required to have final variables, or a method by
which it can pick up its owning class's members or call its routines.
Nested classes.
Generally that's just a namespace issue. In Java, a class Fie nested
inside Foo is the top-level class Foo$Fie with some compiler magic to
ensure it's used correctly, which leads to funny stuff like

Foo.Fie object = new Foo().new Fie();

which gets turned into the bytecode equivalent of

Foo$Fie object = new Foo$Fie(new Foo());

Hm.
Primitive types -- in other words, the int<->Integer dichotomy we
all know and love in Java; such also exists in C++ and IINM C#. I'm
not sure if Smalltalk has such a concept, or not; Smalltalk allows
overrides on numbers. (In Java one might contemplate 2.toString(),
for example!)
In Smalltalk you ask the 1 object to count to 10 for a loop. It makes
sense there, it would not feel "right" in the C family...

Or anywhere else that I know of offhand.
Arbitrary integer size. The only language I know having this is
Common LISP.
java.math.BigInteger, but the operations you can perform are limited.

Hm. OK, "arbitrary number size with transparency".
Quite a few language implementations provide arbitrary precision
integers, I'll just mention Smalltalk again.
>
Thread-level variable/value scoping. In Java this is done using the
ThreadLocal class, but is not (AFAICT) supported by the language
proper.
Yes, and that leads to a problem where if you forget to null a
ThreadLocal you can "leak" objects.

Ugh.

Well, unfortunately for Java it's all too easy to
leak certain objects, though the only one coming to
mind are FileInputStream, FileOutputStream, FileReader,
and FileWriter. Forget to close them before the variable
goes out of scope and they remain open forever, as far as
I can tell.

(Maybe that'll be fixed in a subsequent rev. I don't know.)
One might even contemplate function-level scoping, but that would
only be useful if one can create new functions on the fly and modify
these values; otherwise, they might as well be static.
As long as you make sure you never use a private static member
elsewhere than in that particular method, it can play the role of a
function-level method.
Persistability. In Java one can implement Serializable or
Externalizable, and generate output from an object. I've always
considered this a bit of a weird hack but it can come in handy, and
forms one leg of the Java EJB implementation.
Persistability is left as an excercise to libraries in most languages.

True, and in that library one usually has a base class.
Volatile field. In Java there is a volatile keyword. I don't know
its precise semantics but it applies to fields.
In Java it's generally a hint to the optimizer NOT to optimize away or
make any assumptions about access to a field.
C#'s event handling emulates this concept to some extent using the
+= operator, though I doubt they do it all that generally -- or all
that well.
Well it's closer to a list of function pointers, sorry delegates; not
much more than Java's more explicit (or cumbersome if you like) event
interfaces can do.

Operator overloading has two issues: it's far more convenient to
write something like

Matrix m1, m2;

Matrix m3 = m1 * m2;

instead of

Matrix m3 = m1.multiplyBy(m2);

or

Matrix m3 = Matrix.multiply(m1, m2);

but it's harder for the compiler and the user to parse.
So it's a tradeoff.

The main problem I have with Swing event handling is
that occasionally it's not clear when I have to tell the
listeners that I've done something to a class which manages
a bunch of listeners. Also, ideally, one would not need
to fire off the listeners in sequence -- though without
explicitly spawning subthreads that would be difficult
in Java.

The main problem with C# event handling is that I don't
know its ramifications, but I consider delegates a bit silly,
mostly because of the Java++ fiasco. That was not COOL,
Microsoft. :-)
Integrated database access (and how tightly). C++ has none at all,
though of one can use various third-party libraries. Java has some
base-level API -- the java.sql.* and javax.sql* library.
Well, those are general library APIs that require native or
socket-based implementation by vendors or third parties.

What you talk about is better represented by "inline" SQL in the form
of SQLJ or Oracle's Pro*C and related products.

There's the issue of how to handle schema changes, as well; that's
probably why nobody wants to tightly integrate anymore. I can't really
blame 'em.

It boils down to how much should be in the language (syntax, compiler,
runtime) and how much should be left to libraries. E.g. he has a "no"
for garbage collection in C++, but there are libraries for that sort
of thing (relying mostly on the ability to override the new, delete
and assignment operators. Even in Java you often have a choice of
garbage collector algorithms in a runtime.

Hm; I'll have to research that. Apart from the aforementioned stream
issues and the occasional "oops I left the thing in the global
Collection" issue, though, I've not had to do much with garbage
collection, though I did write a rather poorly-performing cache.

I will definitely have to fiddle with WeakReference at some point,
though it's probably easier just to punt to a solution like
Hibernate or JBossCache (TreeCache) or even Castor/JDO.

Like I said, FOSS has a lot of stuff out there; the main problem
for me is finding it. :-)

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
Sep 1 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: srijit | last post by:
Hello All, I have been seeing this term "duck typing" for quite sometime now. It will be nice if one of us can give an example in Python demonstrating duck typing and/or link to some Python...
12
by: Jason Tesser | last post by:
I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from...
49
by: bearophileHUGS | last post by:
Adding Optional Static Typing to Python looks like a quite complex thing, but useful too: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I have just a couple of notes: Boo...
1
by: Luis Zarrabeitia | last post by:
Hi there. I just tried this test: ==== def f(**kwds): print kwds import UserDict d = UserDict.UserDict(hello="world")
0
by: Paddy | last post by:
The official glossary entry here: http://docs.python.org/tut/node18.html#l2h-46 says: " duck-typing Pythonic programming style that determines an object's type by inspection of its method or...
16
by: Joe Strout | last post by:
Let me preface this by saying that I think I "get" the concept of duck- typing. However, I still want to sprinkle my code with assertions that, for example, my parameters are what they're...
0
by: Tim Rowe | last post by:
2008/11/12 Joe Strout <joe@strout.net>: What do you actually mean by "Quacks like a string"? Supports the 'count()' method? Then you find out if it doesn't when you try to apply the 'count()'...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.