我想创建一个带有字符串和字符串列表的函数,如果字符串列表中没有字符串则返回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库函数。
答案 0 :(得分: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
删除。