【问题标题】:Make a function which returns the original list except the argument创建一个返回除参数之外的原始列表的函数
【发布时间】:2013-11-05 11:12:03
【问题描述】:

我想做一个函数,它接受一个字符串列表和一个字符串,如果字符串列表中没有字符串,则返回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 库函数。

【问题讨论】:

  • 如果模式出现多次怎么办?是否应该全部删除?
  • @tahatmat,假设它只能发生一次。

标签: recursion functional-programming sml


【解决方案1】:

我觉得这个问题不是很适合递归,但是为什么不使用内置的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 删除。

【讨论】:

  • 我不想使用任何库函数。
  • @Alex,如果我可以问,为什么不呢?
猜你喜欢
  • 2011-02-19
  • 2020-08-15
  • 2019-04-14
  • 2015-11-26
  • 2023-01-12
  • 2013-08-03
  • 2016-10-12
  • 1970-01-01
相关资源
最近更新 更多