SML - 在字符串中查找相同的元素

时间:2015-06-08 13:03:52

标签: string list sml

抱歉,我需要你的帮助! 我需要一个函数作为输入

list of (string*string) 

并作为输出返回

list of (int*int)

该函数应该操作列表,使得由相同字符串表示的每个元素必须被相同的数字替换。 例如,如果我插入:

changState([("s0","l0"),("l0","s1"),("s1","l1"),("l1","s0")]);

输出应该是:     val it = [(0,1),(1,2),(2,3),(3,0)]

有人有想法解决这个问题吗? 我真的很感激。非常感谢!

1 个答案:

答案 0 :(得分:0)

这是一种方式:

structure StringKey = 
struct 
  type ord_key = string 
  val compare = String.compare
end

structure Map = RedBlackMapFn(StringKey)

fun changState l =
  let fun lp(l, map, max) = 
        case l 
           of nil => nil
            | (s1,s2)::l' => 
                case (Map.find(map, s1), Map.find(map, s2))
                   of (SOME i1, SOME i2) => (i1, i2)::lp(l', map, max)
                    | (NONE, SOME i) => (max, i)::lp(l', Map.insert(map, s1, max), max+1)
                    | (SOME i, NONE) => (i, max)::lp(l', Map.insert(map, s2, max), max+1)
                    | (NONE, NONE) =>
                        if s1 <> s2
                        then (max, max+1)::lp(l', Map.insert(Map.insert(map, s1, max), s2, max+1), max+2)
                        else (max, max)::lp(l', Map.insert(map, s1, max), max+1)
  in lp(l, Map.empty, 0) end

这里lp获取字符串对列表,将字符串与整数相关联的映射,以及跟踪下一个未使用数字的变量max。在每次迭代中,我们在地图中查找两个字符串。如果找到它们,则返回该整数,否则,使用下一个可用的整数。最后一种情况,地图中不存在字符串,我们需要检查字符串是否相等,如果输入为[("s0", "s0")],我们会期望[(0, 0)]。如果它们相等,我们将它们映射到相同的数字,否则创建不同的数字。

如果您不熟悉仿函数,前5行将创建一个满足ORD_KEY签名的结构。您可以在

的文档中找到更多详细信息
  1. http://www.smlnj.org/doc/smlnj-lib/Manual/ord-map.html
  2. http://www.smlnj.org/doc/smlnj-lib/Manual/ord-key.html#ORD_KEY:SIG:SPEC
  3. 通过将ReBlackMapFn仿函数应用于StringKey结构,它会创建一个新的地图结构(实现为红黑树),将字符串映射到'a类型的事物< / p>