f# - fsharp 通过方括号引用来赋值

标签 f#

对于 fsharp 数组,我们可以执行以下操作:

let tt = Array.zeroCreate 10 
tt.[5] <- 4
Console.WriteLine("{0}", tt.[5])

结果将为 4

我想实现我自己的提供类似接口(interface)的类。 作为示例,我写了这个:

type MyByteArray = class
    val Data : byte[]

    new (size) =
        {
            Data = Array.init size (fun x -> byte(x))
        }

    member this.Item (id) = 
        this.Data.[id]
end

let test = MyByteArray 5
Console.WriteLine("{0}", test.[2]) /// <- this one woks
test.[2] <- 33uy /// <- this one fails

可以通过[]接收元素,但不能设置为item.[id] <- newValue .

如何实现这样的接口(interface)?

谢谢。

最佳答案

您可以像这样使用 getter 和 setter 定义索引器:

member this.Item 
  with get id = this.Data.[id]
  and set id v = this.Data.[id] <- v

如果我编写代码,我也会使用主构造函数语法:

type MyByteArray(size) =
  let data = Array.init size (fun x -> byte(x))  
  member this.Item 
    with get(id) = data.[id]
    and set id v = data.[id] <- v

关于f# - fsharp 通过方括号引用来赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280932/

相关文章:

f# - 在哪里可以找到最新的 F# 核心库引用?

f#: program to calculate difference between dates

f# - 使用不可变列表创建具有链接节点的邻接列表

macos - 如何在我的 visual studio 代码中使用 FSI for F# 4?

f# - System.MissingMethodException : Method not found: 'FSharp. Data.HttpResponse

f# - 将 OCaml 转换为 F# : Differences between typing and type inference

C# Deedle AggregateRowsBy/数据透视表示例

asynchronous - F# 中的 F# 连续循环

f# - cons::F# 中序列的运算符?

f# - F# 是否从后向前迭代元组?