JJunior
JJunior

Reputation: 2849

Reading and recreating a list based on its values

I want to create a subset of my list based on its values. For example:

List (AA AB BA DC AD)

I want a list which has all values of atoms in it starting from 'A' So Answer should be:

(AA AB AD)

I can do this currently by traversing through the whole list and converting each value to another list and reading the first value and then recreating the list.

This is an awfully complex solution.

Is there any method in Scheme which can read the first character of the string in a list and remove the element?

Upvotes: 0

Views: 134

Answers (1)

Vijay Mathew
Vijay Mathew

Reputation: 27204

Check if your Scheme implementation has a procedure called filter or something like that. If not you can define one yourself:

(define (filter p lst)
  (let loop ((lst lst) (res ()))
    (if (null? lst)
        (reverse res)
        (if (p (car lst))
            (loop (cdr lst) (cons (car lst) res))
            (loop (cdr lst) res)))))

Using filter to get all atoms that start with 'A':

> (filter (lambda (x) (char=? (string-ref (symbol->string x) 0) #\A)) 
          '(AA AB BA DC AD))
=> (AA AB AD)

Upvotes: 5

Related Questions