-2

我想创建一个函数,它接受一个字符串列表和一个字符串,NONE如果字符串列表中没有字符串,则返回,否则返回SOME与原始字符串列表相同的字符串列表,只是它不包含初始字符串(模式):

fun my_function (pattern, source_list) =
  case source_list 
    of [] => NONE
    | [x] => if pattern = x then SOME [] else NONE
    | x::xs => 
      if pattern = x 
      then SOME (xs) 
      else SOME (x) :: my_function (pattern, xs) (* this is wrong, what to do here?*)


val a = my_function ("haha", ["12", "aaa", "bbb", "haha", "ccc", "ddd"]) (* should be SOME ["12", "aaa", "bbb", "ccc", "ddd"]*)  
val a2 = my_function ("haha2", ["123", "aaa", "bbb", "haha", "ccc"]) (*should be NONE*)
val a3 = my_function ("haha3", ["haha3"]) (* should be SOME []*)

我对第三种情况感到困惑:x::xs => ....那里应该做什么?请注意,我不想使用任何 sml 库函数。

4

1 回答 1

0

这个问题并没有让我觉得非常适合递归,但是为什么不使用内置List.filter函数来摆脱列表pattern呢?如果过滤列表的长度与原始列表相同,则该模式没有出现在列表中:

fun my_function (pattern, source_list) = let
  val flist = List.filter (fn x => pattern <> x) source_list
  in
    if (length flist) = (length source_list) then NONE
    else SOME flist
  end

请注意,所有出现的pattern都会被 删除List.filter

于 2013-10-26T10:33:15.397 回答