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**,則會導致轉換應用於字串的每個字元。

廣告