gpt4 book ai didi

ocaml - 如何在数组和字符串上编写仿函数?

转载 作者:行者123 更新时间:2023-12-01 07:27:54 26 4
gpt4 key购买 nike

我想使用以下签名使我的代码在字符串和数组(实际上是任何可索引类型)上通用:

module type Indexable = sig
type 'a t
val get : int -> 'a t -> 'a
end
module MyCode (I : Indexable) = struct ... end
但当然,我不能将我的签名应用于字符串,如下所示:
module StrMyCode = MyCode(struct
type 'a t = string
let get i a = a.[i]
end)

有没有办法解决这个问题?或者也许是不同的方法?我知道在最坏的情况下我可以使用字符数组,但我宁愿从丑陋的 Actor 阵容中保存我的代码,这是我之前想到的事情,所以我想为此得到一个明确的答案。

最佳答案

GADT 可以与仿函数化方法一起使用:

module type Indexable = sig
type 'a t
val get: int -> 'a t -> 'a
end

module MyCode(I:Indexable) = struct
let head x = I.get 0 x
end

数组当然可以制作 Indexable琐碎地:
module IndexableArray = struct
type 'a t = 'a array
let get i x = x.(i)
end

对于字符串,您可以只使用带有单个构造函数的 GADT。但是请注意,您必须为 get 放置一些类型注释以强制多态类型(否则,推断类型为 int -> char t -> char ):
module IndexableString = struct
type 'a t = String: string -> char t
let of_string s = String s
let get: type a. int -> a t -> a =
fun i s -> match s with String s -> s.[i]
end

关于ocaml - 如何在数组和字符串上编写仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14289069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com