Functional programming 理解标准ML中多态类型的传递

Functional programming 理解标准ML中多态类型的传递,functional-programming,sml,Functional Programming,Sml,我正在做一些练习来帮助我理解SML,发现我很难理解泛型/多态类型是如何传递到函数中的 我得到以下初步信息: datatype 'a tree = Leaf | Node of 'a tree * 'a * 'a tree val testTree = Node (Node (Node (Leaf, ("a", 107), Leaf), ("c", 417), Node (Leaf, ("e", ~151), Node (Leaf, ("o", ~499), Leaf))), ("s", 35

我正在做一些练习来帮助我理解SML,发现我很难理解泛型/多态类型是如何传递到函数中的

我得到以下初步信息:

datatype 'a tree = Leaf | Node of 'a tree * 'a * 'a tree


val testTree = Node (Node (Node (Leaf, ("a", 107), Leaf), ("c", 417), Node (Leaf, ("e", ~151), Node (Leaf, ("o", ~499), Leaf))), ("s", 35), Node (Leaf, ("u", ~387), Node (Leaf, ("y", 263), Leaf)))

fun nameCompare (n1: name, n2: name) : order = String.compare (n1, n2)

fun treeLookup cmp =
let
  fun lkup (x, btree) =
     case tree of
        Leaf => NONE
      | Node (lt, y, rt) =>
           (case cmp (x, y) of
               LESS => lkup (x, lt)
             | EQUAL => SOME y
             | GREATER => lkup (x, rt))
in
  lkup
end
当我尝试调用
treeLookup
时,我继续得到类型匹配错误。 例如,这就是我所说的

treeLookup nameCompare ("a", testTree)
我会犯这样的错误

treeLookup nameCompare ("a", testTree);
                             ^^^^^^^^
Type clash: expression of type
(string * int) tree
cannot have type
string tree
在将树传递给treeLookup时,我需要做什么才能满足树的类型?

在树中

a' : ("a", 107)
treeLookup
对每个元素和您传递的元素调用
cmp
。您传入了接受两个字符串和一个字符串的
nameCompare
,以及作为字符串的
“a”
。这意味着您的树中应该只有字符串

要解决此问题,您可能希望使树成为一个映射,只在对的第一个值上进行有效比较:

| Node (lt, (k,v), rt) =>
           (case cmp (x, k)
可能还会更改定义:

datatype 'k 'v tree = Leaf | Node of 'k 'v tree * ('k * 'v) * 'k 'v tree

或者,您可以将比较函数更改为采用
('a*'b)
,但这意味着,例如,您需要使用一个元素
('a',107)
,该元素将尝试匹配两个字段。

您正在将一个字符串与树中的一个项目进行比较,该项目是
字符串*int

您可以随时更改比较函数;差不多

fun nameCompare (n, (k,v)) = String.compare (n1, k)

应该可以。

看起来我不得不选择第二个选项,因为我无法更改树结构。