计算和打印SML中的匹配值

问题描述

对于分配的参数,我不能使用模式或折叠,这是解决较大问题的特殊方法的玩具示例。

运行代码时,自然会得到一个“ 0”。所以问题是,如何获得a_count的最终值?

fun num_counter(numbers: int list,a_number: int) =
     let val count = 0
             in
                 let fun count_num(numbers: int list,a_count: int) =
         if null numbers
         then 0
         else if (hd numbers) = a_number
         then count_num(tl numbers,count + 1)
         else count_num(tl numbers,count)
     in
     count       
     end
     end

解决方法

您的代码有几个问题:

  1. 您的递归函数count_num永远不会被调用。
  2. 您的递归通过返回0而不是结果来终止 到目前为止,您已经积累了经验(a_count)。
  3. 参数a_count之间有些混淆,正如我 被理解保存a_numbercount的出现次数 在第二行声明。

这里有一些更正:

fun num_counter(numbers: int list,a_number: int) = let
    fun count_num(numbers: int list,count: int) =
      if null numbers
      then count  (*  reached the end of the list =>
                      returned the number of occurences computed  *)
      else if (hd numbers) = a_number
      then count_num(tl numbers,count + 1)
      else count_num(tl numbers,count)
in
    count_num (numbers,0)  (*  first call of count_num,count initiated to 0  *)
end;

还请注意,您可以使用模式匹配来增强内容的可读性 您的递归函数:

fun num_counter(numbers: int list,a_number: int) =
  let fun count_num([],count) = count
        | count_num(i :: tl,count) =
          count_num(tl,if i = a_number then count + 1 else count)
  in
      count_num (numbers,0)
  end;
,

您可以使用折叠将其写得更短:

fun num_counter (numbers,a_number) =
    let fun count (b_number,total) =
            if a_number = b_number
            then total + 1
            else total
    in foldl count 0 numbers
    end

这里foldl带有三个参数:函数count在访问每个数字时累积结果,b_number中的numberstotal的初始值是0,数字要翻过来,numbersfoldl访问了最后一个号码后,它将使用total中的最后一个累积作为结果。

foldl本身是定义的like this

fun foldl f e []      = e
  | foldl f e (x::xr) = foldl f (f(x,e)) xr

或者您可以filter并购买length,费用会更高:

fun num_counter (numbers,a_number) =
    length (filter (fn b_number => a_number = b_number) numbers)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...