RE: [xsl] What is the best way to cast integer to string in XSLT2?

Subject: RE: [xsl] What is the best way to cast integer to string in XSLT2?
From: "Michael Kay" <mhk@xxxxxxxxx>
Date: Tue, 13 May 2003 02:03:17 +0100
> Hi Mike and Jeni,
> With Saxon 7.5 I'm getting an error on the following:
>      <xsl:value-of select="concat(position(), '. ', ., '&#xA;')"/>
> "Type error in first argument of call to concat():
>   Required type is xs:string; supplied value has type xs:integer"
> 1. Why doesn't the XSLT processor perform an implicit cast 
> from integer to string? This is quite natural, as any atomic 
> type has a string representation and can be converted to string.

I agree with you that it would be very natural for concat() to do
implicit conversion of its arguments to strings. It's interesting that
the "+" operator in Java is exceptional in this regard; it is the only
weakly typed operator in an otherwise strongly-typed language. I found
that in my library of test cases, supplying non-string arguments to
concat() was one of the most comment causes of type errors. (In
backwards compatibility mode, of course, it is still allowed.) I have
argued in the WG that concat() should be treated specially, but most of
my colleagues preferred to keep the rules consistent with other
functions. I suspect some were concerned that it might be the thin end
of the wedge towards a gradual reintroduction of weak typing into the
language generally.

There are probably two main justifications for not allowing function
arguments always to be cast to the required type. The first is error
checking - as the number of types increases, the risk increases of doing
a calculation that is different from the one the user actually intended.
The second is polymorphism. XPath 2.0 doesn't allow functions (as
distinct from operators) to be polymorphic, but some people would like
to keep the option open to allow it in future, and weak typing is not
really compatible with polymorphism.

Most languages end up being a bit pragmatic about this, and XPath is no
different. In the latest draft, we changed all the functions that accept
or return URIs to use the xs:string type instead of xs:anyURI, because
it was simply too much of a pain to keep casting strings to URIs and
back (though Java makes you do just that). For numerics, we introduced a
set of promotion rules that allow arithmetic to mix the different
numeric types.

There would be no technical difficulty in defining concat(), like
string(), to take item() rather than xs:string as its argument type.
It's just a question of persuading people that it deserves to be treated
as a special case.

The place for such comments, of course, is the public-qt-comments list.

Michael Kay

 XSL-List info and archive:

Current Thread