Removing all duplicate members from a list in scheme - scheme

I am trying to remove duplicates in a list, using recursion. This is what I have. It only removes the first duplicate, not all of them.
My idea is to look at the first member, check if its a member of the rest of the list, if so, call the function again. If not, create a list with the first member and the result from calling the function again. I don't understand why it doesn't remove all the duplicates.
(define (removeDupes L)
(cond ((null? L) ())
((list? (member (car L) (cdr L))) removeDupes (cdr L))
(#T (cons ((car L) (removeDupes (cdr L)))))))
This is what I modified it to, and it works!! And I understand what was wrong with the cons. It needs two parameters and I only gave it one. I still have no Idea why the third line did not work....
(define (removeDupes L)
(cond ((null? L) ())
((list? (member (car L) (cdr L)))(removeDupes(cdr L)))
(#T (cons (car L) (removeDupes (cdr L))))))

There are multiple errors in your code, but the one that's probably causing the problem you've reported here is that your parentheses are wrong in the third line. You're trying to call removeDupes but your code doesn't actually do so; instead the value in that case ends up being (cdr L). Can you see why?
When you fix this, you'll find that your code starts producing errors. For the one you're likely to encounter first: take a careful look at how you're invoking cons on the last line. For the one you're likely to encounter next: remember that () is not self-evaluating in Scheme.
(I think this sort of thing is much harder to miss if you take care with the spacing and layout of your code. Put spaces between the elements of every list, for instance. Until you get so familiar with this stuff that these mistakes stop happening, you might want to make a habit of checking the parentheses any time you run across a mysterious error: have you missed a ( at the start of an expression, or put an extra ( before the arguments of a function, or forgotten the extra level of parens round a cond clause, or etc. etc. etc. Don't worry: after a while it'll stop happening...)

Related

Is there a limit to how many car and cdr we can chain in Scheme?

Some answers on here just say that you can chain multiple car and cdr to reduce the clutter they create so, you could use (cadr (list)) instead of (car (cdr (list) )), but I have tried chaining multiple car and cdr and sometimes it will stop working on like the 5th one or something, I tried googling if there is a limit or something but couldnt find any answers.
specifically my problem shows here -> trying to get 7 from a list only using car and cdr.
list is (1(2(3(4(5(6(7)))))))))
(display (car(car(cdr(car(cdr(car(cdr(car(cdr(car (cdr (car (cdr '(1(2(3(4(5(6(7)))))))))))))))))))))
-> shows 7
(display (caadadadadadadr '(1(2(3(4(5(6(7)))))))))
-> shows error
Is this not how this works?
You aren't specific about which Scheme you're using. But for every Scheme implementation I'm aware of, there's a limit to how many car/cdr compositions are provided. In R5RS, for example, we see
library procedure: cddddr pair
These procedures are compositions of
car and cdr, where for example caddr could be defined by
(define caddr (lambda (x) (car (cdr (cdr x))))).
Arbitrary compositions, up to four deep, are provided. There are
twenty-eight of these procedures in all.

Filtering a list with indexes MIT-scheme

Is there a good way to filter a list using each element and its index in scheme? This is how I'm doing it now, but it seems overly complex
(map cdr
(filter (lambda (index-and-element)
(filter-proc (car index-and-element)
(cdr index-and-element)))
(map cons (iota (length l))
l)))
Looks perfectly fine to me. Except, perhaps you meant map cdr...
Personally I like very short variable names whenever possible, so instead of index-and-element I'd just use ie -- they are unimportant, it's just some wiring, so make them as invisible as possible.
Another possibility is to use (map list ...) initially, not (map cons ...), and then inside the lambda to use (apply filter-proc ie). this way filter-proc is called with two arguments, so it can be defined (define (filter-proc idx elt) ...).
And after all that, since it is indeed complex and error-prone to type all this anew each time, we'd just define a higher-order function for this so it is easier to use, like
(define (indexed-filter ipred lst)
(filter (lambda (ie)
(apply ipred ie))
(map list (iota (length lst))
lst)))
;; (define (ipred idx elt) ....) ; returns Bool
and use it whenever the need arises.
I've intentionally left out the (map cadr ...) post-processing step, since you could sometimes want to get the indices of the matching elements instead of the elements themselves. So that would be part of the calling "protocol" so to speak -- whether you're interested in indices, elements, or both, you'd just tweak the call to this general procedure.

scheme : What's imperative features?

The bottom code is to remove adjacent duplicate elements from a sorted list L.
(define a
(lambda (L)
(cond
((null? L) L)
((null? (cdr L)) L)
((eqv? (car L) (car (cdr L))) (a (cdr L)))
(else (cons (car L) (a (cdr L)))))))
Question is "Write a similar function that uses the imperative features of Scheme to modify L 'in place,' rather than building a new list. Compare that to the code above in terms of brevity, conceptual clarity, and speed.
But I don't understand clearly what imperative features. Plz help.
The question asks for you to use some or all of the following procedures to write the solution: set-car!, set-cdr!, set!, etc. In this context, the imperative features refer to those Scheme procedures that mutate data - using them you can modify a list structure "in place", meaning: without creating a new list, instead directly modifying the list passed as parameter.
Notice that all the procedures' names mentioned end with a ! (pronounced: bang!), this is to warn the programmer that they will change the object received as parameter. Contrast this with the procedures you've been using up until now, that won't change the object and if necessary will return a new object with the requested modification - a functional programming style, unlike the imperative programming style that will happen when you start using bang!-procedures.
Take a look at section 3.3 Modeling with Mutable Data in the SICP book, it will explain in detail how to deal with operations that mutate data.

Scheme program to turn every element of a list into atoms

I need a program that takes a list as input and turns every element found in the list into atoms. Here's what i have so far but i keep running into errors.
(define make-lat
(lambda (l)
(cond
((null? l) (quote ()))
(else
(cond
((list? (car l))
(cons (caar l)
make-lat (cdr l)))
(else
((atom? (car l))
(cons (car l)
(make-lat(cdr l)
)))))))))
Can someone help me out?
Your code looks a little disorganized to me, and I think you might want to think about following the steps in the How To Design Programs Design Recipe:
Step one: can you write a purpose statement for your program? It should say what the function does.
Step two: can you write a contract? It should say what kind of data the program takes in, and
what it produces. You've got to be specific, here, and any kind of data that you specify must either be built-in or have an explicit "data definition".
Step three: write some test cases! Provide a sample input, and the output that you expect.
For more design recipe goodness, check out How To Design Programs.
Your question looks like homework.
Here's a couple of things you could do to try and debug.
Use the Repl to try out parts of the function. E.g if in a cond, you are checking for null, you could do it on the REPL too.
(null? '(1 2 3)) or (null? '())
Check individual S-Exps. Are you sure that every function that you call has an opening and closing parens.
As a tip, simplify your cond's. You don't need to nest conds. You can put all conditions one by one.

Scheme homework help

Okay so I have started a new language in class. We are learning Scheme and i'm not sure on how to do it. When I say learning a new language, I mean thrown a homework and told to figure it out. A couple of them have got me stumped.
My first problem is:
Write a Scheme function that returns true (the Boolean constant #t) ifthe parameter is a list containing n a's followed by n b's. and false otherwise.
Here's what I have right now:
(define aequalb
(lambda (list)
(let ((head (car list)) (tail (cdr list)))
(if (= 'a head)
((let ((count (count + 1)))
(let ((newTail (aequalb tail))))
#f
(if (= 'b head)
((let ((count (count - 1)))
(let ((newTail (aequalb tail))))
#f
(if (null? tail)
(if (= count 0)
#t
#f)))))))))))
I know this is completely wrong, but I've been trying so please take it easy on me. Any help would be much appreciated.
A trick I picked up from Essentials of Programming Languages is to always write recursive list functions by handling the two important cases first: null (end of list) and not null.
So, the basic structure of a list function looks something like this:
(define some-list-function
(lambda (list)
(if (null? list)
#f
(do-some-work-here (head list)
(some-list-function (tail list))))))
Usually you (1) check for null (2) do some work on the head and (3) recur on the tail.
The first thing you need to do is decide what the answer is for a null list. It's either #t or #f, but which? Does a null list have the same number of a as b?
Next, you need to do something about the recursive case. Your basic approach is pretty good (although your example code is wrong): keep a count that goes up when you see a and down when you see b. The problem is how to keep track of the count. Scheme doesn't have loops* so you have to do everything with recursion. That means you'll need to pass along an extra counter variable.
(define some-list-function
(lambda (list counter)
(if (null? list)
; skip null's code for a second
Now you have to decide whether the head is 'a or not and increment count if so (decrement otherwise). But there's no count variable, just passing between functions. So how to do it?
Well, you have to update it in-line, like so:
(some-list-function (tail list) (+ 1 count))
By the way, don't use = for anything but numbers. The newer, cooler Lisps allow it, but Scheme requires you to use eq? for symbols and = for numbers. So for your 'a vs 'b test, you'll need
(if (eq? 'a (head tail)) ...)
; not
(if (= 'a (head tail)) ...)
I hope this helps. I think I gave you all the pieces, although there are a few things I skipped over. You need to change the null case now to check count. If it's not = 0 at the end, the answer is false.
You should also maintain a separate flag variable to make sure that once you switched to 'b, you return #f if you see another 'a. That way a list like '(a a a b b a b b) won't pass by mistake. Add the flag the same way I added counter above, by adding another function parameter and passing along the value at each recursive call.
Finally, if your teacher really isn't giving you any help, and won't, then you might want to read a basic book on Scheme. I haven't used any of these myself, but I've heard they're good: The Scheme Programming Language, How to Design Programs or err umm I thought there was a third book online for free, but I can't find it now. I guess if you have lots of extra time and want to blow your mind, you can read Structure and Interpretation of Computer Programs. It teaches a little Scheme and lot about programming languages.
*It does have some of these things, but it's better to ignore them for now.
Isn't list a keyword? I always used to use "alist" as my variable name to get around it.
You could use counters like you are, but I might go for a recursive function that has the following conditions:
params: alist
returns true if the list is nil,
false if the first element is not a,
false if the last element is not b,
(aequalb (reverse (cdr (reverse (cdr alist))))) ;; pick off the front and back, and recurse
in this case, you may need to write a reverse function... can't remember if it was there already.
Also, from a syntax perspective, you don't need to introduce a lambda expression...
(define (foo arg) (+ 1 arg))
is a function called foo, takes a number, and adds one to it. You would call it (foo 1)
I'd take a look at andmap, take and drop, which (between them) make this pretty trivial. Oh and at least for now, I'd probably try to forget that let even exists. Not that there's anything particularly wrong with it, but I'd guess most of the problems you're going to get (at least for a while) don't/won't require it.
Here's a first-cut that may help you. It handles the basic problem, although you need to test to make sure there are no edge cases.
Anyway, the function checks several conditions:
It first checks a base case (recursive functions need to have this, to avoid the possibility of infinite recursion). If the input list is empty then return true (assumption is that all items have been removed, so at this point we are done).
Then the code checks to see if the first items is an a and the last is a b. If so, it strips these chars off and recurses.
Otherwise something is wrong, so the function returns false
(define (aeqb items)
(cond
((equal? '() items) #t)
((and (equal? "a" (car items))
(equal? "b" (car (reverse items))))
(aeqb (cdr (reverse (cdr (reverse items))))))
(else #f)))
(aeqb '("a" "a" "b" "b"))

Resources