Finding duplicate elements in a Scheme List using recursion - recursion

I'm trying to create a function that will check a list of numbers for duplicates and return either #t or #f. I can only use car, cdr and conditionals, no cons.
This is what I have so far but it's giving me the error "car: contract violation expected: pair? given: #f"
(define (dups a)
(if (null? a)
#f
(if (= (car a)(car(dups(cdr a))))
#t
(dups (cdr))
)
)
)
I'm new to both scheme and recursion, any help/advice would be greatly appreciated.

Your second if doesn't make much sense. I'm assuming you wanted to check whether (car a) appears somewhere further down the list, but (car (dups (cdr a))) doesn't give you that. Also, (car (dups ...)) is a type-issue since dups will return a boolean instead of a list, and car is expecting a list (or actually, a pair, which is what lists are composed of).
What you need is a second function to call in the test of that second if. That function takes an element and a list and searches for that element in the list. Of course, if you're allowed, use find, otherwise implement some sort of my-find - it's quite simple and similar to your dups function.

Related

Scheme Recursion Through Arguments

I'm brand new to Scheme, and this is a homework question, so please no outright answers.
Here is my question:
Write a recursive procedure (any? arg1 arg2 ...), where the argi's are
boolean values. any? returns #t if any of its arguments is #t, and #f
otherwise.
These are the constraints:
You may not use the built-in procedures map, apply, list->vector, or
vector->list in any procedure. Likewise, do not use a let expression
or an internal define expression in any procedure, unless the problem
says otherwise.
Here is the code I have:::
(define any?
(lambda args
(if (null? args)
#f
(if (equal? #t (car args))
#t
(any? (cdr args))))))
My problem seems to be that I am hitting an infinite loop on the last line (any? (cdr args)). I am not sure why that is happening. My professor said a hint was to write any? as an interface procedure, and write a helper that handles the list. I am not sure how that would help.
Any advice would be appreciated!
EDIT: I have added new code. I am still getting an infinite loop.
(define any?
(lambda args
(any-helper args)))
(define any-helper
(lambda (list)
(if (null? list)
#f
(if (equal? #t (car list))
#t
(any? (cdr list))))))
I thought by writing lambda args in my main function, I would be passing a list to my helper function. I'm not sure if that is actually happening. I am not sure how to ensure that I don't recurse over '() infinitely.
Consider the steps taken by the function application (any? #f). This leads to a recursive call to (any? '()). Next, it checks to see if the argument list in this call, '(()), is null? (which it isn't, since it is a list containing '()). (equal #t '(()) is also false, so it keeps recursing since you're calling it with the same number of arguments instead of reducing the size of the input in each recursive call.
Hey, this is my 100th answer!
When you have a symbol argument or a dotted list as prototype the last argument, in your case args, contains the rest of the given operands.
Imagine you evaluate (any? #f 5 6) then args would be (#f 5 6). Since first argument is #f you then call (any? '(5 6)) instead of (any? 5 6).
Usually you would make a named let or a local procedure to handle a one argument list so that your code actually would work, but since you are not allowed to you need to use apply to do this instead.
(apply any? '(#f 5 6)) is the same as (any? #f 5 6). You can think of apply as the opposite as dotted list/symbol prototype in a procedure definition.
PS: Your update using any-helper would work perfectly if you recurse with any-helper instead of any?.

SICP 2.64 order of growth of recursive procedure

I am self-studyinig SICP and having a hard time finding order of growth of recursive functions.
The following procedure list->tree converts an ordered list to a balanced search tree:
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts)
right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree this-entry left-tree right-tree)
remaining-elts))))))))
I have been looking at the solution online, and the following website I believe offers the best solution but I have trouble making sense of it:
jots-jottings.blogspot.com/2011/12/sicp-exercise-264-constructing-balanced.html
My understanding is that the procedure 'partial-tree' repeatedly calls three argument each time it is called - 'this-entry', 'left-tree', and 'right-tree' respectively. (and 'remaining-elts' only when it is necessary - either in very first 'partial-tree' call or whenever 'non-left-elts' is called)
this-entry calls : car, cdr, and cdr(left-result)
left-entry calls : car, cdr, and itself with its length halved each step
right-entry calls: car, itself with cdr(cdr(left-result)) as argument and length halved
'left-entry' would have base 2 log(n) steps, and all three argument calls 'left-entry' separately.
so it would have Ternary-tree-like structure and the total number of steps I thought would be similar to 3^log(n). but the solution says it only uses each index 1..n only once. But doesn't 'this-entry' for example reduce same index at every node separate to 'right-entry'?
I am confused..
Further, in part (a) the solution website states:
"in the non-terminating case partial-tree first calculates the number
of elements that should go into the left sub-tree of a balanced binary
tree of size n, then invokes partial-tree with the elements and that
value which both produces such a sub-tree and the list of elements not
in that sub-tree. It then takes the head of the unused elements as the
value for the current node"
I believe the procedure does this-entry before left-tree. Why am I wrong?
This is my very first book on CS and I have yet to come across Master Theorem.
It is mentioned in some solutions but hopefully I should be able to do the question without using it.
Thank you for reading and I look forward to your kind reply,
Chris
You need to understand how let forms work. In
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
left-tree does not "call" anything. It is created as a new lexical variable, and assigned the value of (car left-result). The parentheses around it are just for grouping together the elements describing one variable introduced by a let form: the variable's name and its value:
(let ( ( left-tree (car left-result) )
;; ^^ ^^
( non-left-elts (cdr left-result) )
;; ^^ ^^
Here's how to understand how the recursive procedure works: don't.
Just don't try to understand how it works; instead analyze what it does, assuming that it does (for the smaller cases) what it's supposed to do.
Here, (partial-tree elts n) receives two arguments: the list of elements (to be put into tree, presumably) and the list's length. It returns
(cons (make-tree this-entry left-tree right-tree)
remaining-elts)
a cons pair of a tree - the result of conversion, and the remaining elements, which are supposed to be none left, in the topmost call, if the length argument was correct.
Now that we know what it's supposed to do, we look inside it. And indeed assuming the above what it does makes total sense: halve the number of elements, process the list, get the tree and the remaining list back (non-empty now), and then process what's left.
The this-entry is not a tree - it is an element that is housed in a tree's node:
(let ((this-entry (car non-left-elts))
Setting
(right-size (- n (+ left-size 1))
means that n == right-size + 1 + left-size. That's 1 element that goes into the node itself, the this-entry element.
And since each element goes directly into its node, once, the total running time of this algorithm is linear in the number of elements in the input list, with logarithmic stack space use.

Procedure? keyword in scheme

I am new to functional programming and I have a piece of code like the following:
(procedure? (car (list cdr)))
Value: #t
I do not understand why this returns true. cdr is a procedure, but what is the car of the list cdr? I do not understand. Can anyone explain?
Thanks
list turns its contents into a list. So (list cdr) is just a list of the element cdr, which itself is a procedure. car gets the first element of a list. So (car (list x)) == x for any x.
This simplifies our problem to (procedure? cdr). Since cdr is clearly a procedure, this returns true.

Racket: Identifying tail recursion?

I wrote two different functions in racket to determine whether a list of numbers is ascending:
(define (ascending list)
(if (<= (length list) 1)
#t
(and (< (car list) (car (cdr list))) (ascending (cdr list)))))
(define (ascending-tail list)
(ascending-tail-helper #t list))
(define (ascending-tail-helper prevBool rest)
(if (<= (length rest) 1)
prevBool
(ascending-tail-helper (and prevBool (< (car rest) (car (cdr rest)))) (cdr rest))))
I had the hardest time determining whether or not the first ascending was tail recursive, so I rewrote it using what I believe to be tail recursion.
The reason why I retrospectively believe the first one to not be tail recursive is that I believe at each level of recursion, the function will be waiting for the second argument in the "and" statement to return before it can evaluate the boolean expression. Conversely, for ascending-tail-helper, I am able to evaluate the lesser than expression before I do my recursive call.
Is this correct, or did I make myself even more confused than before?
DrRacket can help you determine whether a call is in tail position or not. Click the "Syntax Check" button. Then move the mouse pointer to the left parenthesis of the expression in question. In your example I get this:
The purple arrow shows that the expression is in tail-position.
From the manual:
Tail Calls: Any sub-expression that is (syntactically) in
tail-position with respect to its enclosing context is annotated by
drawing a light purple arrow from the tail expression to its
surrounding expression.
You are correct, in the first version the recursive call returns to and, whereas in the second version the recursive call is a tail call.
However, and is a macro, and is generally expanded using if
(define (ascending list)
(if (<= (length list) 1)
#t
(if (< (car list) (car (cdr list)))
(ascending (cdr list))
#f)))
which is tail recursive.
One of the requirements for a function to be in tail position is that it's return value be usable as the return value of the parent function without modification or inspection. That is, the parent function should be able to return immediately, having evaluated the tail position statement.
On first appearance, your first function,inspects the return value of ascending. It seems that doesn't return ascending's value but, instead, a value derived from it. However, according to the relevant section of the R5RS spec, the final expression in an and statement is in tail position. (When I'm properly awake, I know this)
So you are wrong.
http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%_sec_3.5
(Note: edited to correct my initial hasty answer).
Racket's documentation on tail positions says that the place to check what's in tail position and what's not is the documentation for the particular form:
Tail-position specifications provide a guarantee about the asymptotic space consumption of a computation. In general, the specification of tail positions goes with each syntactic form, like if.
Racket's docs on and say (emphasis added):
(and expr ...)
If no exprs are provided, then result is #t.
If a single expr is provided, then it is in tail position, so the
results of the and expression are the results of the expr.
Otherwise, the first expr is evaluated. If it produces #f, the result
of the and expression is #f. Otherwise, the result is the same as an
and expression with the remaining exprs in tail position with respect
to the original and form.

Library function for sorting based on a predicate

Does a function exist in the Clojure library for filtering a collection, and returning a pair of collections, one of which contains the items where the predicate returned true, and the other which contains the items where the predicate returned false?
For example:
(let [[yays nays] (some-fn pred coll)] ... )
More or less, I am looking for a way to sort based on the predicate, rather than throw away (like with filter or remove).
(Note: I know that a solution is to call filter and remove on the collection separately; I just would like to know if there is a builtin function that can accomplish this more efficiently).
(Edit: seq-utils/separate doesn't qualify as more efficient. It evaluates the predicate twice for each item.)
clojure.core/group-by
If you want maximum performance you'll want to do this using loop/recur, something like:
(defn separate-by [pred coll]
(loop [yays nil
nays nil
s (seq coll)]
(if s
(let [item (first s)
test (pred item)]
(if test
(recur (conj yays item) nays (next s))
(recur yays (conj nays item) (next s))))
{:yays yays :nays nays})))
The reason this is most efficient is that the loop/recur enables you to iteratively build the two output lists without any extra memory allocations (which would happen if you repeated updated a map for example) or reference overhead (which would happen if you used two atoms to accumulate the results).

Resources