【问题标题】:Create a repeat function in SML在 SML 中创建重复函数
【发布时间】:2021-11-15 07:19:17
【问题描述】:

我正在创建一个名为 repeat 的函数,它接受两个 int 列表 lst1lst2。假设lst2只有非负整数,根据第二个列表lst2指示的数字重复第一个列表lst1中的整数。如果两个列表都是空的,则返回一个空列表。您可能需要一个本地函数。

示例:
repeat ([1,2,3], [4,0,3]) -> [1,1,1,1,3,3,3]

我在开始使用此功能时遇到了一些麻烦。 xs后面应该放什么?

fun repeat(lst1, lst2) =
    case lst1 of
      [] => []
    | x::xs' => [] (* what should I put here *)

【问题讨论】:

    标签: recursion sml smlnj


    【解决方案1】:

    与任何递归问题一样,您的基本情况是什么?我想说在这种情况下,两个列表都是空的,它给你一个空列表。

    fun repeat([], []) = []
    

    如果一个是空的而另一个不是呢?那是失败的。让我们定义一个在发生这种情况时可以抛出的异常。

    exception MismatchedArguments;
    
    fun repeat([], []) = []
      | repeat([], _) = raise MismatchedArguments
      | repeat(_, []) = raise MismatchedArguments
    

    现在真正的问题是我们在剩下的时间里做什么。幸运的是,SML 可以轻松地对两个列表进行模式匹配并提取它们的第一个元素。

    exception MismatchedArguments;
    
    fun repeat([], []) = []
      | repeat([], _) = raise MismatchedArguments
      | repeat(_, []) = raise MismatchedArguments
      | repeat(x::xs, y::ys) = ...
    

    此时,我们需要一个递归函数来重复列表中的一个元素一定次数。与整体功能一样,这里我们看到递归的两个标志:至少一个基本“退出”条件,以及通过将n 更新为@987654325 向基本条件收敛的更新步骤@。

    exception MismatchedArguments;
    
    fun repeat([], []) = []
      | repeat([], _) = raise MismatchedArguments
      | repeat(_, []) = raise MismatchedArguments
      | repeat(x::xs, y::ys) = 
          let
            fun repeat'(_, 0) = []
              | repeat'(x, n) = x :: repeat'(x, n - 1)
          in
            ...
          end
    

    现在,我们只需要将它们放在一起,将xy 输入到repeat',然后将其与再次调用repeat 的结果与xsys 连接起来。通过这样做,我们会收敛到repeat([], []) 的基本情况,我们可能会收敛到引发MismatchedArguments 异常的不匹配场景。

    exception MismatchedArguments;
    
    fun repeat([], []) = []
      | repeat([], _) = raise MismatchedArguments
      | repeat(_, []) = raise MismatchedArguments
      | repeat(x::xs, y::ys) = 
          let
            fun repeat'(_, 0) = []
              | repeat'(x, n) = x :: repeat'(x, n - 1)
          in
            repeat'(x, y) @ repeat(xs, ys)
          end
    

    现在repeat([1, 2, 3], [4, 0, 3]) 将产生[1, 1, 1, 1, 3, 3, 3]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多