在球拍中查找列表中的出现元素

时间:2014-05-20 19:03:38

标签: list sorting recursion scheme racket

假设(list "apple" "orange" "apple" "grape" "orange")并生成(list (list 2 "apple") (list 2 "orange") (list 1 "grape"))

最常见的水果将首先出现在生产列表中。 在关系的情况下,按照字母顺序增加对水果的捆绑对进行排序。

在本地使用map,filter,foldr和quicksort等抽象列表功能。没有递归。

如果没有递归,我不知道怎么做。

我是这样写的:

(define (function list)
   (cond
      [(empty? list) empty]
      [else
        (local
           (define (helper1 a b)
             (cond
               [(equal? a b) a]
               [else b]))
           (define T (foldr helper1 (first list) (rest list)))
           (define (count a)
             (cond
               [(equal? a T) true]
               [else false]))
           (define new-list (quicksort (length (filter count list)) >))]

2 个答案:

答案 0 :(得分:0)

最有效的方法是使用(可变)哈希表:

 
(define (count-by-type lst)
  ; create hash
  (define h (make-hash))
  ; update hash, creating entries if needed, otherwise adding 1 to existing entry
  (map (lambda (e) (hash-update! h e add1 0)) lst) 
  ; create list of (count key) elements from hash and sort accordingly
  (sort (map (lambda (e) (list (cdr e) (car e))) (hash->list h))
        (lambda (x y) (or (> (car x) (car y)) 
                          (and (= (car x) (car y)) (string<? (cadr x) (cadr y)))))))

测试:

> (count-by-type (list "apple" "orange" "apple" "grape" "orange"))
'((2 "apple") (2 "orange") (1 "grape"))

答案 1 :(得分:0)

我刚刚重新开始own answer from a previous question。这似乎是一个类似的任务,但没有struct

使用哈希只需要通过未排序的列表进行一次传递,然后生成一个列表,然后使用特殊的< - 按功能排序,然后是水果排序。

这些提示是针对功能性解决方案的。首先对参数(sort list-of-fruits string>?)进行排序。 按降序和结果的对位。

鉴于列表至少有一个元素:

(let rec ((cur (car sorted-fruits)) (cnt 1) (lst (cdr sorted-fruits)) (acc '()))
  (cond ((equal? cur (car lst)) (rec cur (add1 cnt) (cdr lst) acc))
        (else (rec (car lst) 1 (cdr lst) (cons (list cnt cur) acc)))))

这会产生一个带有计数的升序列表。

如果你再次排序:

(sort list-of-counts-and-fruit (lambda (x y) (>= (car x) (car y)))
Racket中的

sort是稳定的。这意味着如果您在列表中有两个具有相同计数的数字,它们将以其原始顺序结束。原始顺序是升序动物顺序,因此结果按计数降序排序,然后命名升序。

我猜你的程序可以通过将它们链接在一起来制作,也许使用let来存储中间体,使表达式更短,更易读。

相关问题