Q语言 - 类型铸造

通常需要将某些数据的数据类型从一种类型更改为另一种类型.标准的转换函数是"$"二元运算符.

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

  • 按符号名称指定所需数据类型

  • 按字符指定所需数据类型

  • 通过短值指定所需的数据类型.

将整数转换为浮点数

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

q)a:9 18 27

q)$[`float;a]     / Specify desired data type by its symbol name, 1st way
9 18 27f

q)$["f";a]        / Specify desired data type by its character, 2nd way
9 18 27f

q)$[9h;a]         / Specify desired data type by its short value, 3rd way
9 18 27f

检查是否全部三个操作是等价的alent,

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

尝试使用键入的单词`symbol或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

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