I'm having some issues with this problem I've been given. It's not homework, it's actually a problem I've encountered at a test and to deepen my understanding I would like to solve it successfully.

The problem is: make a procedure element-count that takes a list of pairs "lst" and an element "el" and returns a list of pairs where, if the element "el" exists in "lst" as the first member, then the second member gets increased by 1. Otheriwse we add to the end of "lst" a pair (cons el 1). The wanted output: element-count '((a 2)) b) -> '((a 2 (b 1))

This is what my code so far looks like:

#lang sicp
(define (append list1 list2)
  (if (null? list1)
      list2
      (cons (car list1) (append (cdr list1) list2))))

(define (count-element lst el)
  (cond ((eq? (car lst) el) (+ (cdr lst) 1))
  (else (append lst (cons (el 1))))))

The first issue I'm having is that it tells me that "b" is undefined. Obviously, b doesn't need to be defined since I want it in my output. How should I fix this? The environment I'm working in is DrRacket. The main question is how should I go about defining a list of pairs? Or is my code actually okay? Lists and pairs are still quite confusing to me so I apologize for silly questions.

1 Answers

3
Cam On Best Solutions

You are pretty close to the correct solution; I think there is just some confusion about how lists and pairs are defined. Here's an implementation and usage of count-element that does what you want:

(define (count-element lst el)
  (cond ((eq? (car lst) el) (+ (cdr lst) 1))
  (else (append lst (list (cons el 1))))))

(count-element (list (cons 'a 2)) 'b)

There are two things to note.

First, the way to define a list of pairs is like this:

(list (cons 'a 1) (cons 'c 2))

or

'((a . 1) (c . 2))

Second, this is the correct way to use your append method:

(append lst (list (cons 'b 1)))

or

(append lst '((b . 1)))

That's because append is defined so that you pass in two lists, and it combines them into a single new list. That's why the second parameter is a list containing the pair you want to append.