【发布时间】:2012-01-11 23:36:35
【问题描述】:
我有以下示例:
type Stream (capacity) =
let data = Array.zeroCreate capacity
member private s.position = ref 0
static member private encoder = new Text.UTF8Encoding()
static member private write (x, o, a : byte[]) = for i = 0 to 3 do a.[o + i] <- byte((x >>> 24 - i * 8) % 256)
static member private write (x, o, a : byte[]) = for i = 0 to 1 do a.[o + i] <- byte((x >>> 24 - i * 8) % 256s)
static member private write (x : string, o : int, a : byte[]) = Stream.encoder.GetBytes(x, 0, x.Length, a, o)
static member format (x : int, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
static member format (x : int16, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
static member format (x : string, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
首先,很抱歉代码非常混乱,我只是 F# 的初学者。如您所见,三个format 重载仅在参数类型上有所不同,而它们的主体是相同的(尽管调用write 的不同重载)。是否有可能以某种方式将格式函数减少为一个,也许是内联的?
如果我完全忽略了这里的重点,我深表歉意,但我找不到关于此事的太多信息。
【问题讨论】:
-
这似乎是pattern matching 可能更合适。
-
有没有办法不用拳击x?
-
这是一个很好的问题...您编写此程序的方式看起来更像是一个 OO 程序而不是函数式程序。
-
T0yv0 在这里使用存储序列化函数的类型字典,但他肯定每种类型都有一个序列化函数:gist.github.com/1082622
标签: types f# arguments overloading implicit