You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SML中如何统计列表内最小数值的出现次数?

在SML中完全可以实现统计列表最小数值的出现次数,你可以按以下方法实现:

实现方法一:复用你已有的occurrences函数

先实现求列表最小值的工具函数,再把求得的最小值传入你写的次数统计函数即可。

1. 实现求列表最小值的函数

注意空列表不存在最小值,你可以选择抛出异常或者返回0,这里以抛出内置Empty异常为例:

fun minList nil = raise Empty
  | minList [x] = x
  | minList (x::xs) = 
    let val minRest = minList xs 
    in if x < minRest then x else minRest end;

2. 优化你的occurrences函数(可选)

你原有的写法是正确的,也可以用模式匹配替代hd/tl调用,写法更符合SML的惯用风格:

fun occurrences(nil, n)=0
|   occurrences(x::xs, n) =
    if x = n then occurrences(xs,n) + 1
    else occurrences(xs,n);

3. 组合实现统计最小数出现次数的函数

fun countMinOccurrences nil = 0 (* 空列表直接返回0,也可以按需求改为抛出异常 *)
|   countMinOccurrences ls = occurrences(ls, minList ls);

测试示例

输入countMinOccurrences [2, 1, 4, 1, 5, 1];,输出结果为3。


实现方法二:单次遍历实现(效率更高)

如果不想遍历两次列表(一次求最小值、一次统计次数),可以在单次遍历中同时记录当前最小值和出现次数,更适合处理长列表:

fun countMinOccurrences nil = 0
|   countMinOccurrences (x::xs) = 
    let
        fun helper (nil, currMin, count) = count
          | helper (y::ys, currMin, count) =
            if y < currMin then helper(ys, y, 1)
            else if y = currMin then helper(ys, currMin, count + 1)
            else helper(ys, currMin, count)
    in
        helper(xs, x, 1)
    end;

内容的提问来源于stack exchange,提问作者ulysessg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:54:05