[xquery-talk] Roman numeral kata in XQuery
andrew.j.welch at gmail.com
Thu May 12 00:37:48 PDT 2011
On 12 May 2011 01:51, Mattio Valentino <mattio.valentino at gmail.com> wrote:
> I hope this isn't too odd of a request.
> I wanted a little XQuery practice so I decided to try to port some
> code katas. I did the Roman numeral one first.
> Would anyone mind reviewing the solution I have here?
Looks good to me.
There are a couple of small things:
- you could use eq instead of = when comparing single items, eg $input
eq 'M'. This will cause an exception if for some reason either side
becomes a sequence of multiple items instead of a single one...
whereas the set operator '=' will just carry on working and is likely
to produce incorrect results.
- you could use the 'as' to type your variables: let $numbers as
xs:integer+ := ....
An alternative to the if-then-else that you ask about could be done like this:
declare variable $letters as xs:string+ := ('I', 'V', 'X', 'L', 'C', 'D', 'M');
declare variable $numbers as xs:integer+ := (1,5,10,50,100,500,1000);
($numbers[index-of($letters, 'I')], 0)
The two sequences are global variables so they only get created once,
and then you use the position (index-of) of the letter in its sequence
to get the corresponding number. The ( ...., 0) is a common way of
defaulting to a value (zero here) if the first part returns nothing.
More information about the talk