目录

Q语言 - 类型转换(Type Casting)

通常需要将某些数据的数据类型从一种类型更改为另一种类型。 标准的转换函数是“$” dyadic operator

使用三种方法从一种类型转换为另一种类型(字符串除外) -

  • 通过其符号名称指定所需的数据类型
  • 按字符指定所需的数据类型
  • 通过短值指定所需的数据类型。

将整数转换为浮点数

在以下将整数转换为浮点数的示例中,所有三种不同的转换方式都是等效的 -

q)a:9 18 27
q)$[`float;a]    /Specify desired data type by its symbol name, 1<sup>st</sup> way
9 18 27f
q)$["f";a]       /Specify desired data type by its character, 2<sup>nd</sup> way
9 18 27f
q)$[9h;a]        /Specify desired data type by its short value, 3<sup>rd</sup> way
9 18 27f

检查这三个操作是否相同,

q)($[`float;a]~$["f";a]) and ($[`float;a] ~ $[9h;a])
1b

将字符串转换为符号

将字符串转换为符号反之亦然。 让我们用一个例子来检查 -

q)b: ("Hello";"World";"HelloWorld")   /define a list of strings
q)b
"Hello"
"World"
"HelloWorld"
q)c: `$b                              /this is how to cast strings to symbols
q)c                                   /Now c is a list of symbols
`Hello`World`HelloWorld

尝试使用键控字符号或符号11h将字符串强制转换为符号将失败,类型错误 -

q)b
"Hello"
"World"
"HelloWorld"
q)`symbol$b
'type
q)11h$b
'type

将字符串转换为非符号

将字符串转换为符号以外的数据类型的方法如下 -

q)b:900              /b contain single atomic integer
q)c:string b         /convert this integer atom to string “900”
q)c
"900"
q)`int $ c           /converting string to integer will return the
                     /ASCII equivalent of the character “9”, “0” and
                     /“0” to produce the list of integer 57, 48 and
                     /48.
57 48 48i
q)6h $ c             /Same as above
57 48 48i
q)"i" $ c            /Same a above
57 48 48i
q)"I" $ c
900i

因此,要将整个字符串(字符列表)强制转换为单个数据类型x需要我们指定表示数据类型x的大写字母作为$运算符的第一个参数。 如果以任何其他方式指定x的数据类型,则会导致将强制转换应用于字符串的每个字符。

↑回到顶部↑
WIKI教程 @2018