从SML中的列表中删除重复项

mac*_*aca 6 recursion functional-programming sml smlnj

我刚开始学习SML中的函数式编程,我想知道如何将以下两个函数组合成一个函数.函数isolate使用辅助函数'removed'删除任何类型列表('a)的重复项.

fun isolate [] = []
  | isolate (l as x::xs) = x::isolate(remove(x,xs))

fun remove (x,[]) = []
  | remove (x,l as y::ys) = if x = y then remove(x,ys) else y::remove(x,ys)
Run Code Online (Sandbox Code Playgroud)

因此,为了更好地理解SML中的构造,如何在isolate中包含函数remove?这看起来似乎微不足道,但我已经考虑过了,无法弄明白.谢谢您的帮助!

qap*_*hla 8

一种方法是仅定义remove内部isolate.

fun isolate [] = []
  | isolate (l as x::xs) =
      let fun remove (x,[]) = []
            | remove (x,l as y::ys) = if x = y
                                      then remove(x,ys)
                                      else y::remove(x,ys)
      in
        x::isolate(remove(x,xs))
      end
Run Code Online (Sandbox Code Playgroud)

或者,为了使重复数据删除成为一个函数,尽管所有这些都是使用库函数List.filter来做同样的事情remove.

fun isolate [] = []
  | isolate (x::xs) = x::isolate(List.filter (fn y => y <> x) xs)
Run Code Online (Sandbox Code Playgroud)