gpt4 book ai didi

oop - 在 OCaml 的 OOP 构造中动态确定类型

转载 作者:行者123 更新时间:2023-12-01 00:07:48 24 4
gpt4 key购买 nike

我正在学习 OCaml 的 OOP 结构并在今天部分实现了这一点,直到我意识到我不知道如何在不使用对象外部的 type 关键字的情况下表示多态匹配语句。

class bar (param:string) =
object (code)

end;;

class foo param =
object (code)
initializer
match param with
string -> Printf.printf "param is a string"
| bar -> Printf.printf "param is a bar"
end;;

let b = new bar "a string";;
let f1 = new foo "test";;
let f2 = new foo b;;

是否可以即时确定传入的对象类型?

最佳答案

那个匹配除了将'param'绑定(bind)到'string'之外什么也没做,ocaml应该说第二个匹配没有被使用。我相信您必须使用变体类型来进行匹配。下面是一个使用多态变体类型的示例。

class bar (param:string) =
object (code)
end

class foo param =
object (code)
initializer
match param with
| `String str -> Printf.printf "param is a string"
| `Bar bar -> Printf.printf "param is a bar"
end

let b = new bar "a string"
let f1 = new foo (`String "test")
let f2 = new foo (`Bar b)

关于oop - 在 OCaml 的 OOP 构造中动态确定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/633200/

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