代码之家  ›  专栏  ›  技术社区  ›  Mat Kelly

在OCaml中动态创建对象

  •  4
  • Mat Kelly  · 技术社区  · 17 年前

    我试图通过使用编译代码而不是顶级代码来学习OCaml;然而,许多在线示例代码似乎对后者有吸引力。

    我想在下面的对象方法中创建一个新的Foo。此代码未编译,引用了doFooProc定义的语法错误。

    class bar =
    object (self)
     method doFooProc = (new Foo "test")#process
    end;;
    
    class foo (param1:string)=
    object (self)
     method process = Printf.printf "%s\n" "Processing!"
     initializer Printf.printf "Initializing with param = %s\n" param1
    end;;
    

    此外,“let”语法在类定义中似乎并不友好。为什么呢?

    class bar =
    object (self)
     method doFooProc = 
      let xxx = (new Foo "test");
      xxx#process
    end;;
    
    class foo (param1:string)=
    object (self)
     method process = Printf.printf "%s\n" "Processing!"
     initializer Printf.printf "Initializing with param = %s\n" param1
    end;;
    

    2 回复  |  直到 17 年前
        1
  •  2
  •   nlucaroni    17 年前

    您基本上是正确的,但可能会将语法与模块系统混淆,或者考虑其他语言。考虑到我的考虑,你应该是好的!

    在每个对象的方法中 在下面这段代码不编译, 引用的语法错误 doFooProc定义。

    小写“foo”表示对象,模块为大写。此外,必须将foo的定义置于调用它的对象之上。你应该得到一份工作 Unbound class foo 如果发生这种情况。

    class bar =
    object (self)
     method doFooProc = (new foo "test")#process
    end;;
    

    此外,“let”语法在类定义中似乎并不友好。为什么呢?

    因为你没有匹配的 in ,而是有一个分号。那就行了。此外,您可以删除这些额外的参数,但这并不重要。

    class bar =
    object (self)
     method doFooProc = 
      let xxx = (new Foo "test") in
      xxx#process
    end;;
    

    比如说,如果foo中的一个方法被实例化 逃避由此产生的问题 在中对类定义进行排序

    对这就像编写相互递归的函数和模块,您可以使用 and 关键词。

    class bar =
      object (self)
        method doFooProc = (new foo "test")#process
      end
    
    and foo (param1:string) = 
      object (self)
        method process = Printf.printf "%s\n" "Processing!"
        initializer Printf.printf "Initializing with param = %s\n" param1
      end
    
        2
  •  2
  •   Rémi    17 年前

    对于两个相互递归的类,使用and关键字

    class bar =
      object (self)
        method doFooProc = 
          let xxx = (new foo "test") in
          xxx#process
      end
    and foo (param1:string)=
      object (self)
        method process = Printf.printf "%s\n" "Processing!"
        initializer Printf.printf "Initializing with param = %s\n" param1
        method bar = new bar
      end;;`
    
    推荐文章