在OCaml的OOP构造中即时确定类型 [英] Determining type on the fly in OCaml's OOP construct
本文介绍了在OCaml的OOP构造中即时确定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习OCaml的OOP构造,并在今天实现了部分实现,直到我意识到我不知道如何在不使用对象外部使用type关键字的情况下表示多态匹配语句.
I am learning about OCaml's OOP constructs and partially implemented this today until I realized I have no idea how to represent a polymorphic match statement without using the type keyword outside of the object.
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;;
是否可以实时确定传递的对象类型?
Is it possible to determine the type of object passed in on-the-fly?
推荐答案
该匹配除了将'param'绑定到'string'之外没有做任何事情,ocaml应该说不使用第二个匹配项.我相信您必须使用变体类型来进行匹配.以下是使用多态变体类型的示例.
That match isn't doing anything but binding 'param' to 'string', ocaml should say that the second match isn't used. I believe you'll have to use variant types to do the matching. Below is an example using polymorphic variant types.
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)
这篇关于在OCaml的OOP构造中即时确定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文