Writing an alternating series checker in racket - recursion

I am trying to make a program which determines if an inputted list alternates in sign. For example, my program would return true if given the list(s): [-1, 5, -10] or [5, -17, 25]. The program would return false if given the list(s): [-1, -5, 6] or [1, -2, -6].
I've tried making a simple cond statement which checks the sign of the first number in the list and then after checks the second number in the list to make sure the first number was positive and the second number was negative or the first number was negative and the second number was positive.
(define (alternating-signs-in-list? lst)
(cond
[(> (first lst) 0)
(cond [(< (first (rest lst)) 0) (alternating-signs-in-list? (rest lst))])]
[(< (first lst) 0)
(cond [(> (first (rest lst)) 0) (alternating-signs-in-list? (rest lst))])]
[else false]))
I expected the code presented to work but was met with an error stating:
first: expects a non-empty list; given: empty
This error occurred when I made the following check-expect:
(check-expect (alternating-signs-in-list? (cons 1 (cons -5 (cons 50 empty)))) true).
Why is the following error occurring and is there an easy fix I can make to get my code to start working. Thank you.

The trick is to compare pairs of elements at the same time (first and second of the list), until the list is exhausted. The error you're receiving is because you forgot to handle the empty-list case, and for this problem in particular, we also need to handle the case when the list has a single element left.
Before proceeding, it's useful to implement a same-sign? procedure, it's easy if we leverage the sgn procedure (that returns the sign of a number), and if we assume that 0 is positive:
(define (same-sign? n1 n2)
; they have the same sign if their `sgn` value is the same
(= (if (zero? n1) 1 (sgn n1))
(if (zero? n2) 1 (sgn n2))))
The main procedure goes like this:
(define (alternating-signs-in-list? lst)
(cond ((or (empty? lst) (empty? (rest lst))) #t) ; empty list / single element case
((same-sign? (first lst) (second lst)) #f) ; they are NOT alternating
(else (alternating-signs-in-list? (rest lst))))) ; advance recursion
Alternatively, we can also write the above using just boolean connectors:
(define (alternating-signs-in-list? lst)
(or (empty? lst)
(empty? (rest lst))
(and (not (same-sign? (first lst) (second lst)))
(alternating-signs-in-list? (rest lst)))))
Either way, it works as expected:
(alternating-signs-in-list? '(-1 5 -10))
=> #t
(alternating-signs-in-list? '(5 -17 25))
=> #t
(alternating-signs-in-list? '(-1 -5 6))
=> #f
(alternating-signs-in-list? '(1 -2 -6))
=> #f

Related

getting error :: rest: expects a non-empty list; given: () in dr racket when checking tests

I'm trying to write a function that checks if a given list is spiraling (numbers going from negative to positive while the abs value of the numbers is strictly increasing)
EX:
(check-expect
(spiraling? (cons 1 (cons -10 (cons 100 empty))))
true)
Im not entirely sure even where my error is so i made slight adjustments in my writing that hasnt done anything.
(define (spiraling? list-of-int)
(cond
[(empty? list-of-int) true]
[(and (number? (first list-of-int))
(empty? (rest list-of-int))) true]
[(and (< (abs (first list-of-int))
(abs (first (rest (first list-of-int)))))
(cond
[(and (> 0 (first list-of-int))
(< 0 (first (rest (first list-of-int)))))true]
[(and (< 0 (first list-of-int))
(> 0 (first (rest (first list-of-int)))))true]
[else false]))
(cond
[(empty? list-of-int) true]
[else (spiraling? (rest list-of-int))])]))
(check-expect
(spiraling? (cons 1 (cons -10 (cons 100 empty))))
true)
(check-expect
(spiraling? (cons -1 (cons 2 (cons -3 (cons 4 empty)))))
true)
(check-expect
(spiraling? (cons 99 (cons -100 (cons 100 empty))))
false)
(check-expect
(spiraling? (cons 0 (cons -10 (cons 100 empty))))
false)
But instead it comes out as:
:: rest: expects a non-empty list; given: ()
Your program has many incoherences.
First, the argument of the function should be a list of integers, but sometimes you use it as a list of lists, for instance when you write:
(abs (first (rest (first list-of-int)))))
in fact (first list-of-int) should return an integer (the first element of the list), but then you apply to it rest, which is an operator that applied to a non empty list returns the list without the first element. And this is the reason of the error message (“rest expect a non-empty list but received 1”).
If you want the second element of a list, you can do (first (rest list)), or, better, (second list). These are basic operators of the language.
Second, in the second branch of the cond, you check to see if the first element of the list is a number, but this check is not repeated in the third branch, even if you use both the first and the second elment as numbers. So the test is useless, since it is applied only in certain cases to certain elements of the list. You should apply to all or none of the elements, to be consistent.
Third, in the last branch of the cond, in the last two lines, you check again if the list is empty, but at this point of the program the list is certainly not empty, since you have tested at least two elements!
Here is a possible solution (without checking if all the elements are numbers):
(define (spiraling? list-of-int)
(if (or (empty? list-of-int) (empty? (rest list-of-int)))
true
(let ((first-element (first list-of-int))
(second-element (second list-of-int)))
(if (or (< first-element 0 second-element)
(> first-element 0 second-element))
(spiraling? (rest list-of-int))
false))))

Trying to understanding recursion and why an error is occurring

I am writing a program which takes in a list and outputs true if the elements in the list alternate signs. For example if the first number is positive, the second number must be negative and then the third number must be positive again and so on.
I've tried implementing a simple cond statement (shown in the code) but keep coming across an error in my check-expect. The error states: first: expects only 1 argument, but found 2.
(define (alternating? lst)
(cond [(empty? lst) true]
[(> (first lst) 0)
(cond [(< (first (rest lst) 0)) (alternating? (rest lst))])]
[(< (first lst) 0)
(cond [(> (first (rest lst) 0)) (alternating? (rest lst))])]
[else false]))
When looking at the code, it looks like first does in fact only take in one argument from the list, but the error says that this is not the case.
On lines 3 and 5, you are correctly calling first with one argument, namely lst:
(first lst)
On lines 4 and 6, you are calling first with two arguments, namely (rest lst) and 0:
(first (rest lst) 0)
I think what you want is this:
(< (first (rest lst)) 0)
; ↑ ↑
instead of this:
(< (first (rest lst) 0))
; ↑ ↑

Check for ascending order of a list in Racket

I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.
'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false
My code so far is:
Image of code
(define (ascending? 'list)
(if (or (empty? list) (= (length 'list) 1)) true
(if (> first (first (rest list))) false
(ascending? (rest list)))))
I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).
I keep getting an error message when I use check-expect that says "application: not a procedure."
I guess you want to implement a procedure from scratch, and Alexander's answer is spot-on. But in true functional programming style, you should try to reuse existing procedures to write the solution. This is what I mean:
(define (ascending? lst)
(apply < lst))
It's shorter, simpler and easier to understand. And it works as expected!
(ascending? '(1 2 3))
=> #t
(ascending? '(1 1 2))
=> #f
Some things to consider when writing functions:
Avoid using built in functions as variable names. For example, list is a built in procedure that returns a newly allocated list, so don't use it as an argument to your function, or as a variable. A common convention/alternative is to use lst as a variable name for lists, so you could have (define (ascending? lst) ...).
Don't quote your variable names. For example, you would have (define lst '(1 2 3 ...)) and not (define 'lst '(1 2 3 ...)).
If you have multiple conditions to test (ie. more than 2), it may be cleaner to use cond rather than nesting multiple if statements.
To fix your implementation of ascending? (after replacing 'list), note on line 3 where you have (> first (first (rest list))). Here you are comparing first with (first (rest list)), but what you really want is to compare (first lst) with (first (rest lst)), so it should be (>= (first lst) (first (rest lst))).
Here is a sample implementation:
(define (ascending? lst)
(cond
[(null? lst) #t]
[(null? (cdr lst)) #t]
[(>= (car lst) (cadr lst)) #f]
[else
(ascending? (cdr lst))]))
or if you want to use first/rest and true/false you can do:
(define (ascending? lst)
(cond
[(empty? lst) true]
[(empty? (rest lst)) true]
[(>= (first lst) (first (rest lst))) false]
[else
(ascending? (rest lst))]))
For example,
> (ascending? '(1 2 3))
#t
> (ascending? '(1 1 2))
#f
> (ascending? '(3 2 4))
#f
If you write down the properties of an ascending list in bullet form;
An ascending list is either
the empty list, or
a one-element list, or
a list where
the first element is smaller than the second element, and
the tail of the list is ascending
you can wind up with a pretty straight translation:
(define (ascending? ls)
(or (null? ls)
(null? (rest ls))
(and (< (first ls) (first (rest ls)))
(ascending? (rest ls)))))
This Scheme solution uses an explicitly recursive named let and memoization:
(define (ascending? xs)
(if (null? xs) #t ; Edge case: empty list
(let asc? ((x (car xs)) ; Named `let`
(xs' (cdr xs)) )
(if (null? xs') #t
(let ((x' (car xs'))) ; Memoization of `(car xs)`
(if (< x x')
(asc? x' (cdr xs')) ; Tail recursion
#f)))))) ; Short-circuit termination
(display
(ascending?
(list 1 1 2) )) ; `#f`

Scheme sum of list

First off, this is homework, but I am simply looking for a hint or pseudocode on how to do this.
I need to sum all the items in the list, using recursion. However, it needs to return the empty set if it encounters something in the list that is not a number. Here is my attempt:
(DEFINE sum-list
(LAMBDA (lst)
(IF (OR (NULL? lst) (NOT (NUMBER? (CAR lst))))
'()
(+
(CAR lst)
(sum-list (CDR lst))
)
)
)
)
This fails because it can't add the empty set to something else. Normally I would just return 0 if its not a number and keep processing the list.
I suggest you use and return an accumulator for storing the sum; if you find a non-number while traversing the list you can return the empty list immediately, otherwise the recursion continues until the list is exhausted.
Something along these lines (fill in the blanks!):
(define sum-list
(lambda (lst acc)
(cond ((null? lst) ???)
((not (number? (car lst))) ???)
(else (sum-list (cdr lst) ???)))))
(sum-list '(1 2 3 4 5) 0)
> 15
(sum-list '(1 2 x 4 5) 0)
> ()
I'd go for this:
(define (mysum lst)
(let loop ((lst lst) (accum 0))
(cond
((empty? lst) accum)
((not (number? (car lst))) '())
(else (loop (cdr lst) (+ accum (car lst)))))))
Your issue is that you need to use cond, not if - there are three possible branches that you need to consider. The first is if you run into a non-number, the second is when you run into the end of the list, and the third is when you need to recurse to the next element of the list. The first issue is that you are combining the non-number case and the empty-list case, which need to return different values. The recursive case is mostly correct, but you will have to check the return value, since the recursive call can return an empty list.
Because I'm not smart enough to figure out how to do this in one function, let's be painfully explicit:
#lang racket
; This checks the entire list for numericness
(define is-numeric-list?
(lambda (lst)
(cond
((null? lst) true)
((not (number? (car lst))) false)
(else (is-numeric-list? (cdr lst))))))
; This naively sums the list, and will fail if there are problems
(define sum-list-naive
(lambda (lst)
(cond
((null? lst) 0)
(else (+ (car lst) (sum-list-naive (cdr lst)))))))
; This is a smarter sum-list that first checks numericness, and then
; calls the naive version. Note that this is inefficient, because the
; entire list is traversed twice: once for the check, and a second time
; for the sum. Oscar's accumulator version is better!
(define sum-list
(lambda (lst)
(cond
((is-numeric-list? lst) (sum-list-naive lst))
(else '()))))
(is-numeric-list? '(1 2 3 4 5))
(is-numeric-list? '(1 2 x 4 5))
(sum-list '(1 2 3 4 5))
(sum-list '(1 2 x 4 5))
Output:
Welcome to DrRacket, version 5.2 [3m].
Language: racket; memory limit: 128 MB.
#t
#f
15
'()
>
I suspect your homework is expecting something more academic though.
Try making a "is-any-nonnumeric" function (using recursion); then you just (or (is-any-numeric list) (sum list)) tomfoolery.

Overloaded function failing giving Compiler recursion error

With the following code, I get #<CompilerException java.lang.UnsupportedOperationException: Can only recur from tail position (NO_SOURCE_FILE:4)> despite the fact that all recurs are in tail positions. If I remove the recur from the one-argument version, it stops complaining. Why is this happening?
(defn remove-duplicates "Removes duplicate elements of lst.
For example, given (1 2 3 1 4 1 2), remove-duplicates returns a sequence
containing the elements (1 2 3 4), in some order."
[lst] (recur (rest lst) (set (first lst)))
[lst uniques] (cond (zero? (count lst)) uniques
:else (cond
(some (partial = (first lst)) uniques)
(recur (rest lst) uniques)
:else
(recur (rest lst) (first lst)))))
You haven't split up the multi-arity bodies right. Should read (defn foo ([x] (...)) ([x y] (...))). This causes the compiler to think you're doing totally different stuff, which probably accounts for your issue.
First of all: you know that all you want is (def remove-duplicates set) or -- if you want a vector -- (def remove-duplicates-vec (comp vec set)), right?
Five things here:
As amalloy noticed, you should've added parens
As kotarak noticed, you can't recur between arities
You can't call (set (first lst)) because set wants coll. If you want, do something like (set (vector (first [1 2 3 2 3]))) but this is neither pretty nor idiomatic
Doing (cond pred1 code1 :else (cond pred2a code2a :else code2b)) could be made simplier: (cond pred1 code1 pred2a code2a :else code2b) -- what you did is treated cond macro as if it were if (which is a built-in as far as I know)
Your last tail-call is also wrong. Assume we've started with [1 2 3 2 1]
When you call it first you have following arguments: ([2 3 2 1] #{1}) (I've skipped the boring part)
Then you have last predicate true, so you go with ([3 2 1] 2) and this is obviously wrong because you wanted ([3 2 1] #{1 2}). You probably want to call (recur (rest lst) (conj uniques (first lst)))
Summing up:
(defn remove-duplicates
([lst] (remove-duplicates (rest lst) #{(first coll)}))
([lst uniques]
(cond
(zero? (count lst)) uniques
(some (partial = (first lst)) uniques)
(recur (rest lst) uniques)
:else
(recur (rest lst) (conj uniques (first lst))))))

Resources