Removing/comparing string value with a list - scheme
I am trying to remove members which exists in a string from a list consisting of those members.
Example:
String: "ABC"
List: ('A 'B 'C 'D)
To do: Remove first element of string from the list
To remove the the element from the string:
I am converting it to a list using:
(car (string->list"ABC")
This gives me character list and first element: #\A
But I do not get how I can remove it from the list as b开发者_Python百科oth values do not compare: the character and list values.
Tried this weird approach which did not work:
((eq? (make-string 1 (car (string->list"ABC"))) (car (list 'A 'B 'C 'D))))
Does not work as string value does not compare with the first list value.
How I can compare & remove the first string alphabet from the original list??
Error as list cannot have string element values:
This is not true. A list can have strings as well as characters as its elements, no problem. You're getting the error because you're using car
on a string, not a list.
(car (list->string(list(car (string->list "ABC")))))
Ok, here you're calling (string->list "ABC")
which gives you a list containing the character A, B and C. Now you're calling car
on that and get the character A back. Up to here there's no problem.
But then you're calling list
on that character getting a list which only contains the character A and then use list-string
to turn this into the string "A"
. This is still perfectly legal. But then you're calling car
on the string "A"
and that's the error because you're calling car
on a string, but car
only accepts a list (well, any pair actually) as its argument.
Since you're trying to compare A against that first element of ('A 'B 'C 'D)
, i.e. 'A
, which is a symbol, you probably want to convert the string "A"
into the symbol 'A
(or the symbol 'A
into the string "A"
). To do this, you can use the function string->symbol
instead of car
.
Once you have the symbol A
, you can easily remove it from the list using the filter
function:
(let ((a (string->symbol (list->string (list (car (string->list "ABC")))))))
(filter (lambda (x) (not (eq? x a))) '(A B C)))
Something like this:
(define lst '(#\a #\b #\c #\d))
(define str (string->list "abc"))
(define (reduce-list lst str)
(cond
[(empty? str) lst]
[else (reduce-list (remove (first str) lst) (rest str))]
)
)
(reduce-list lst str)
Result:
(list #\d)
精彩评论