diff --git a/src/slang/strings/Roman.sl b/src/slang/strings/Roman.sl index 173ce093eb42209859704e7cacd89e66ac9bf185..f492a41fc645b1afaef2718812dda340362b12e1 100644 --- a/src/slang/strings/Roman.sl +++ b/src/slang/strings/Roman.sl @@ -79,3 +79,67 @@ define roman(n) return strlow(Roman(n;; __qualifiers)); } +define roman2int() +%!%+ +%\function{roman2int} +%\usage{Integer_Type=roman2int(String_Type)} +%\synopsis{translates a roman numeral into an integer} +%\description +% This function converts roman numerals into integers. +% The function is case insensitive and array safe. +%\seealso{roman,Roman} +%!%- +{ + variable r=(); + + if (typeof(r)==Array_Type) { + return array_map(Integer_Type,&roman2int,r); + } + + r=strup(r); + + % deal with negative numbers + variable sn=+1; + if (substr(r,1,1)=="-") { + sn=-1; + r=substr(r,2,strlen(r)); + } + + variable vals=Assoc_Type[Integer_Type]; + vals["0"]=0; + vals["I"]=1; + vals["V"]=5; + vals["X"]=10; + vals["L"]=50; + vals["C"]=100; + vals["D"]=500; + vals["M"]=1000; + + variable res=0; + variable i; + for (i=1; i<=strlen(r); i++) { + variable s1=vals[substr(r,i,1)]; + if (i=s2) { + res+=s1; + } else { + res+=s2-s1; + i++; + } + } else { + res+=s1; + } + } + + res=sn*res; + + % sanity check (otherwise we silently return erroneous results for + % illegal roman numerals) + if (r!=Roman(res)) { + throw UsageError,sprintf("%s: %s is not a valid roman numeral",_function_name(),r); + } + + + return sn*res; +}