【问题标题】:How to write a function in SML/NJ that in a given list, counts successive equal elements and returns a list of pairs (value, count)?如何在 SML/NJ 中编写一个函数,在给定列表中计算连续相等元素并返回对列表(值,计数)?
【发布时间】:2023-11-06 05:30:01
【问题描述】:

我必须在 SML/NJ 中编写一个函数,该函数在给定列表中计算连续相等的元素并返回对(值,计数)的列表。函数应该是这样的:

fun group (xs: ''a list): (''a * int) list

我只能使用匿名函数和结构 List、ListPair 和 Math。

我不知道该怎么做。有人可以帮帮我吗?

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:

    一个简单但低效的方法是写this version of group

    val group : ''a list -> ''a list list
    

    并将输出进一步转换为:

    val group_count : ''a list -> (''a * int) list
    

    通过以下方式:

    fun group_count xss = map (fn xs => (hd xs, length xs)) xss
    

    但更有效的方法是编写一个函数span_count

    fun span_count p x [] count = (count, [])
      | span_count p x (y::xs) count =
        if p (x, y)
        then span_count p x xs (count+1)
        else (count, y::xs)
    

    并递归使用它:

    fun group_count [] = []
      | group_count (x::xs) =
        case span_count op= x xs 1 of
          (count, ys) => (x, count) :: group_count ys
    

    【讨论】: