What's wrong with this append? - scheme

Racket is giving me a contract violation for the following code:
(define (fringe x)
(append (car x) (fringe (cdr x))))
Any ideas what's wrong with it?

It happens because (car x) is not returning a list (it's hard to tell for sure without knowing the actual value of x that's rising the error). append is an operation defined between two lists. If you want to add an element at the head of a list, use cons instead of append.
This is what I mean:
(append 1 '(2 3))
=> append: expected argument of type <proper list>; given 1
(append '(1) '(2 3))
=> '(1 2 3)
(cons 1 '(2 3)) ; the recommended way!
=> '(1 2 3)

Related

How to invert the predicate here?

I have the following filter procedure:
; (2) filter
(define (filter test sequence)
; return a list of the elements that pass the predicate test
(let ((elem (if (null? sequence) nil (car sequence)))
(rest (if (null? sequence) nil (cdr sequence))))
(cond ((null? sequence) nil)
((test elem) (cons elem (filter test rest)))
(else (filter test rest)))))
And here would be an example of using it to return the even-numbered elements of a list:
(define even? (lambda (x) (= (modulo x 2) 0)))
(define sequence '(1 2 3 4 5 8 9 11 13 14 15 16 17))
(filter even? sequence)
; (2 4 8 14 16)
Is there a simple way to use the not test to invert the selection? For example, I thought the following might work:
(filter (not even?) sequence)
But it returns an error. I can define odd separately, of course:
(define odd? (lambda (x) (not (even? x))))
But I'm trying not to do this. Is there a way to write the odd procedure without defining it directly, but instead using the not directly like I'm trying to do above?
There is a complement function in Common Lisp that does what I think you are looking for. complement is a higher-order procedure that takes a procedure as its argument, and returns a procedure that takes the same arguments as the input procedure and performs the same actions, but the returned truth value is inverted.
Racket has a similar procedure, negate, and it is easy enough to implement this in Scheme:
(define (complement f)
(lambda xs (not (apply f xs))))
> (filter even? '(1 2 3 4 5))
(2 4)
> (filter (complement even?) '(1 2 3 4 5))
(1 3 5)
> (> 1 2 3 4 5)
#f
> ((complement >) 1 2 3 4 5)
#t
And in Racket:
scratch.rkt> (filter even? '(1 2 3 4 5))
'(2 4)
scratch.rkt> (filter (negate even?) '(1 2 3 4 5))
'(1 3 5)
scratch.rkt> (> 1 2 3 4 5)
#f
scratch.rkt> ((negate >) 1 2 3 4 5)
#t
The general answer to this is to simply compose not and the function you care about. Racket has a compose function which does this, but you can easily write a simple one yourself:
(define (compose-1 . functions)
;; simple-minded compose: each function other than the last must
;; take just one argument; all functions should return just one
;; value.
(define (compose-loop fns)
(cond
((null? fns)
(λ (x) x))
((null? (cdr fns))
(car fns))
(else
(λ (x) ((car fns) ((compose-loop (cdr fns)) x))))))
(compose-loop functions))
Making it efficient and more general takes more work of course.
Then you can define odd? (which is already defined of course):
(define odd? (compose-1 not even)
Or in fact define a more general CL-style complement function:
(define (complement f)
(compose-1 not f))
One option is to write an invert function which will curry things along (so the initial function still accepts one argument) until the final evaluation occurs:
(define invert (lambda (func) (lambda (x) (not (func x)))))
(define sequence '(1 2 3 4 5 6 8 9 11 13 14 15 16 17))
(filter (invert even?) sequence)
; (1 3 5 9 11 13 15 17)

Scheme append function workflow

Hello I am looking at the append function
(define ( append x y )
(if (null? x)
y)
(cons (car x)
(append (cdr x)
y))))
I understand how the list is generated but when the first list x is empty we directly return y,I don't see how we connect it to the first list "x".Does the process go like this (cons a1(cons a2....(cons an y).. )) and how does the program understand to plug in y at (cons an y),Is it because in the end the expression is (cons an-1 ,append (cdr x) y ) and the result of (append (cdr x ),y) is y?
Your function has an error in it such that is in parsing has one closing parens too much in the end. I thin kit's because you close if just after y. Because of that it will always do the last expression and it fails when x is empty.
The correct append looks like this:
(define (append x y)
(if (null? x)
y
(cons (car x)
(append (cdr x)
y))))
I like to explain recursive functions by simplest to general so we start off with the obvious, the base case:
(append '() '(3 4))
This will be #t for x being null? and the result is (3 4). Now lets try with a one element list as x:
(append '(2) '(3 4))
This is #f for x being `null? thus you can substitute it with:
(cons (car '(2))
(append (cdr '(2))
'(3 4)))
We can evaluate the accessors on '(2):
(cons 2 (append '() '(3 4))
Since we did the base case before we know the answer to the append part, which is '(3 4) so we end up with:
(cons 2 '(3 4)) ; ==> (2 3 4)
Lets do a new x:
(append '(1 2) '(3 4))
Here as the previous x is not null? so you substitute with the alternative again:
(cons (car '(1 2))
(append (cdr '(1 2))
'(3 4)))
As the previous time we can evaluate the accessors:
(cons 1
(append '(2)
'(3 4)))
Notice that again we have familiar arguments to append so we could just substitute that with our last result, however I take the step before so you see the pattern you noticed:
(cons 1 (cons 2 (append '() '(3 4)))) ; ==>
(cons 1 (cons 2 '(3 4))) ; ==>
(cons 1 '(2 3 4)) ; ==>
; ==> (1 2 3 4)
So if you have a 12 element x it gets 12 cons nested before hitting the base case and then it evaluates the the inner to the outer since list are always created from end to beginning since the functions need to evaluate their arguments before applying.

multiplying list of items by a certain number 'x'

How would you write a procedure that multiplies each element of the list with a given number (x).If I give a list '(1 2 3) and x=3, the procedure should return (3 6 9)
My try:
(define (mul-list list x)
(if (null? list)
1
(list(* x (car list))(mul-list (cdr list)))))
The above code doesnt seem to work.What changes do I have to make ? Please help
Thanks in advance.
This is the text book example where you should use map, instead of reinventing the wheel:
(define (mul-list lst x)
(map (lambda (n) (* x n)) lst))
But I guess that you want to implement it from scratch. Your code has the following problems:
You should not call list a parameter, that clashes with the built-in procedure of the same name - one that you're currently trying to use!
The base case should return an empty list, given that we're building a list as output
We build lists by consing elements, not by calling list
You forgot to pass the second parameter to the recursive call of mul-list
This should fix all the bugs:
(define (mul-list lst x)
(if (null? lst)
'()
(cons (* x (car lst))
(mul-list (cdr lst) x))))
Either way, it works as expected:
(mul-list '(1 2 3) 3)
=> '(3 6 9)
For and its extensions (for*, for/list, for/first, for/last, for/sum, for/product, for/and, for/or etc: https://docs.racket-lang.org/reference/for.html) are very useful for loops in Racket:
(define (ml2 lst x)
(for/list ((item lst))
(* item x)))
Testing:
(ml2 '(1 2 3) 3)
Output:
'(3 6 9)
I find that in many cases, 'for' implementation provides short, simple and easily understandable code.

Error in scheme when using cadr

Can anyone clarify what this error means?
cadr: expects argument of type <cadrable value>; given (1)
cadr means car and cdr. (i.e, return the car of the cdr of a list). Both the following expressions have the same effect:
> (car (cdr '(1 2 3 4)))
2
> (cadr '(1 2 3 4))
2
(cadr '(1)) will fail because (cdr '(1)) evaluates to null.

Do iterative loop in scheme

New to scheme here and I'm having some trouble learning do loops. I am attempting to make a function that will take in an object and a vector, and then iterate through the vector until it find that object. When the object is found, it would then return a list containing all of the items in the vector before the object. My code is below. All it will return is how many iterations the do loop went through, instead of the list I want it to. If anyone could help me with the syntax, I would greatly appreciate it. Thanks! ( ideally this would return (1 2))
(define(vector-test-iterative X Vector)
(do ((i 0 (+ i 1))) (< i (vector-length Vector))
(if (eqv? X (vector-ref Vector i))
(= i (vector-length Vector))
(cons (vector-ref Vector i) (ls '())))
ls))
(vector-test-iterative '4 #(1 2 4 3 5))
If you're using Racket, then there's no need to use do, which was never popular among schemers anyway. There's a whole range of iterators -- look for for in the docs, and things that start with for. For example, your code boils down to
#lang racket
(define (values-before x vector)
(for/list ([y (stop-before (in-vector vector)
(lambda (y) (eqv? x y)))])
y))
(If you really want to use do, then you're missing a pair of parens around the test, and you should add a binding for the accumulator.)
A solution that uses a named loop. Cleaner (in my opinion!) than the do version and should work on any R5RS Scheme:
;; Extracts the sublist of `lst` up to `val`.
;; If `val` is not found, evaluates to an empty list.
(define (upto val lst)
(let loop ((res null) (lst lst))
(cond ((null? lst) null)
((eq? val (car lst)) (reverse res))
(else (loop (cons (car lst) res) (cdr lst))))))
;; Adapts the above procedure to work with vectors.
(define (vector-upto val vec)
(list->vector (upto val (vector->list vec))))
;; test
(vector-upto 6 #(1 2 3 4 5))
=> #0()
(vector-upto 5 #(1 2 3 4 5))
=> #4(1 2 3 4)
(vector-upto 3 #(1 2 3 4 5))
=> #2(1 2)
(vector-upto 1 #(1 2 3 4 5))
=> #0()

Resources