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

检查所有三个操作是否等效,

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

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