【发布时间】:2013-11-28 00:41:27
【问题描述】:
我正在使用 SML 进行作业编码,并且我已经完成了一些练习题,我觉得我错过了一些东西 - 我觉得我使用了太多 case 语句。这是我正在做的事情以及我遇到的问题的问题陈述。:
-
编写一个函数 all_except_option,它接受一个字符串和一个字符串列表。如果字符串不在列表中,则返回 NONE,否则返回 SOME lst,其中 lst 类似于参数列表,但字符串不在列表中。
fun all_except_option(str : string, lst : string list) = case lst of [] => NONE | x::xs => case same_string(x, str) of true => SOME xs | false => case all_except_option(str, xs) of NONE => NONE | SOME y=> SOME (x::y) -
编写一个函数get_substitutions1,它接受一个字符串列表list(一个字符串列表,替换的列表)和一个字符串s,并返回一个字符串列表。结果包含在替换列表中的所有字符串也有 s,但 s 本身不应该在结果中。
fun get_substitutions1(lst : string list list, s : string) = case lst of [] => [] | x::xs => case all_except_option(s, x) of NONE => get_substitutions1(xs, s) | SOME y => y @ get_substitutions1(xs, s)
-
same_string 是一个提供的函数,
fun same_string(s1 : string, s2 : string) = s1 = s2
【问题讨论】:
-
这是 Coursera 编程语言课程第 2 周作业的一部分。由于在线发布解决方案是违规行为,我要求重新措辞这个问题以更改函数名称,使其与分配不完全匹配。
标签: functional-programming pattern-matching case sml