【问题标题】:How to instantiate a functor in SML?如何在 SML 中实例化函子?
【发布时间】:2013-01-25 16:52:18
【问题描述】:

如果我有以下仿函数,我如何用ListMapFn 实例化它?

functor G(M: ORD_MAP where type Key.ord_key = string) :

【问题讨论】:

    标签: functional-programming sml ml


    【解决方案1】:

    为了详细说明函子的语法,这里有一些例子。

    首先是一些初步声明,以便我们可以处理一些事情。

    signature FOO =
    sig
      val foo : unit -> unit
    end
    
    
    structure FooUnit : FOO =
    struct
      fun foo () = ()
    end
    
    
    structure FooPrint : FOO =
    struct
      fun foo () = print "Foo\n"
    end
    

    现在。当我们创建只接受一个结构作为参数的函子时,如果我们不想写functor FooFn (f : FOO)functor FooFn (structure f : FOO),这是可选的。实际上,这仅适用于函子将一个结构作为参数时:

    (* Optionally to write "structure f : FOO" as there is only one argument *)
    functor FooFn (f : FOO) = struct
      val foo = f.foo
    end
    

    但是,当函子接受两个或更多参数时,必须使用关键字结构。请注意,仿函数也可以采用其他参数,例如整数值。

    (* Note there is no delimiter, just a space and the structure keyword *)
    functor FooFooFn (structure f1 : FOO
                      structure f2 : FOO) =
    struct
      val foo1 = f1.foo
      val foo2 = f2.foo
    end
    

    在应用函子并返回结果结构时,我们也有一些选择。第一个是直截了当的。

    structure f1 = FooFn (FooUnit)
    

    然而,这有点“特例”,因为我们将其定义为“内联”,省略了 structend 部分

    structure f2 = FooFn (fun foo () = print "Inlined\n")
    

    或者我们可以更详细一些,包括structend 部分。然而,这两个都只起作用,因为函子接受一个参数

    structure f2_1 = FooFn (struct fun foo () = print "Inlined\n" end)
    

    当函子接受多个参数时,语法有些相同

    (* Again note there is no delimiter, so we can have it on the same line *)
    structure f3 = FooFooFn (structure f1 = FooUnit structure f2 = FooPrint)
    

    它有点像记录,因为顺序无关紧要

    (* And we can even switch the order *)
    structure f4 = FooFooFn (structure f2 = FooUnit
                             structure f1 = FooPrint)
    

    【讨论】:

      【解决方案2】:

      类似

      structure S = G(ListMapFn(type ord_key = string; val compare = String.compare))
      

      或者,如果您更喜欢命名 ListMap 实例:

      structure ListMap = ListMapFn(type ord_key = string; val compare = String.compare)
      structure S = G(ListMap)
      

      【讨论】:

      • 我认为您与 MLton 的合作有点过头了?至少我还没有看到 SML/NJ 使用 t 作为类型变量 :) 在这种情况下它应该是 type ord_key = string
      • @Jesper.Reenberg:OCaml 和其他人,但你是对的。 :) 已修复。
      • SML/NJ 没有采用这种约定/风格真的很遗憾,它在很多方面都很有用。 MLton 的人用它创造的一些东西有时真的让我吃惊。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 2020-06-07
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多