收集列表中相似项并在列表中查找最常见项的方案 [英] Scheme collecting similar items in a list and finding most common item in a list

查看:36
本文介绍了收集列表中相似项并在列表中查找最常见项的方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个函数,该函数会出现一个元素在列表中出现的次数.例如在列表中: '(a b c b b c c a) 我希望它返回一个嵌套列表:'((a 2) (b 3) (c 3))

I want to make a function that occurs how many times an element occurs in a list. For example in the list: '(a b c b b c c a) I want it to return a nested list with: '((a 2) (b 3) (c 3))

我知道这个函数看起来像这样:

I know the function will look sort of like this:

(define collect-similar
 (lambda (elm ls)
  (cond
   [(null? ls) '()]
   [(equal? elm (car ls))]

我知道我需要继续检查列表,直到它返回空列表的基本情况,我可以使用 cadr 检查列表的其余部分.但我不太确定如何获取值以及如何使其返回嵌套列表.

I know that I need to continue checking through the list until it arrives back at the base case of the null list and I can check the rest of the list by using cadr. But I'm not too sure on how to get the value and how to make it return the nested list.

我要编写的下一个函数查找列表中最常见的元素.例如,在列表 '(a a a a a b c) 上运行该函数将简单地返回 a.我知道我可以使用 collect-similar 函数并找出最高的数字.

The next function I'm trying to write finds the most common element in the list. For example running the function on the list '(a a a a a b c) will simply return a. I know I can make use of the collect-similar function and find which number is the highest.

推荐答案

这个之前已经问过了,只是改编@ChrisJester-Young 的bagify 实现.例如:

This has been asked before, just adapt one of @ChrisJester-Young's bagify implementations. For example:

(define (collect-similar lst) ; a slightly modified `bagify`
  (hash->list
   (foldl (lambda (key ht)               
            (hash-update ht key add1 0))
          '#hash()
          lst)))

(collect-similar '(a b c b b c c a))
=> '((a . 2) (b . 3) (c . 3))

使用 collect-similar 后,很容易找到最常见的元素:

With collect-similar in place, it's simple to find the most common element:

(define (most-common lst)
  (let loop ((alst (collect-similar lst)) ; use previous procedure
             (maxv '(#f . -inf.0)))
    (cond ((null? alst) (car maxv))
          ((> (cdar alst) (cdr maxv))
           (loop (cdr alst) (car alst)))
          (else
           (loop (cdr alst) maxv)))))

(most-common '(a a a a a b c))
=> 'a

这篇关于收集列表中相似项并在列表中查找最常见项的方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆