为什么数组和字符串索引使用略有不同的语法?
例如:
我(以及其他人)认为这很奇怪和令人困惑。
例如:
let _: int = [|1;2;3|].(0)
let _: char = "123".[0]
我(以及其他人)认为这很奇怪和令人困惑。
+
进行整数加法和+.
进行浮点加法完全相同的原因:OCaml放弃了特设多态/函数重载,而索引运算符目前被视为OCaml中的一种函数形式,因此受到与函数相同的限制。x.(n)
重写为Array.get x n
,将x.(n) <- y
重写为Array.set x n y
(如果使用-unsafe
选项编译,则为Array.unsafe_get
和Array.unsafe_set
)。同样,s.[n]
被重写为String.get s n
,而s.[n]<-x
则变为String.set s n x
。Array
模块来定义自己的索引运算符。例如,以下不良建议的技巧将使数组索引从1
开始: module Array = struct
include Array
let get a n = get a (n-1)
let unsafe_get a n
end
;; [|1|].(1)
.
和左括号((
, [
, {
)之间插入至少一个(操作符)字符来定义扩展的索引运算符。let (.?()) dict key = Dict.find_opt dict key
let first (s:string) = s.(0)
let first (a: _ array) = a.(0)