How do i do in Racket a function that replaces the element of a list at the position n by e.
(repl-elem '(a b c d e) 2 d)
should return a d c d e
In order to replace the element with index 2 in a list with a new element 'A,
one can do the following:
#lang racket
(define xs (list 1 2 3 4 5))
(append (take xs 2)
(list 'A)
(drop xs (+ 2 1)))
I'll leave it as an exercise to turn this into a function.
To see "the mechanics behind this list-set" one can use 'named let' recursion:
(define (f L n c)
(let loop ((x 1)
(ol '()))
(cond
[(> x (length L))
(reverse ol)]
[(= x n)
(loop (add1 x) (cons c ol))]
[else
(loop (add1 x) (cons (list-ref L (sub1 x)) ol))])))
Testing:
(f '(a b c d e) 2 'd)
Output:
'(a d c d e)
OP can figure out how it is working.
Related
Write a function that takes a list and a length as input and returns two lists: (1) The first length elements of the input list, and (2) the remainder of the input list. Hint: Use a helper method with an "accumulator" parameter. I'm stuck guys and could really use some help.
I keep getting error when I try to do (split-list '(a b c d e f g) 7) which is the number equal to length otherwise any number less than than that does what its supposed to do
:
Argument #1 '()' to 'car' has wrong type (empty-list)
(split-list '(a b c d e f g) 0) should return '(() (a b c d e f g))
(split-list '(a b c d e f g) 1) should return '((a) (b c d e f g))
(split-list '(a b c d e f g) 3) should return '((a b c) (d e f g))
(define (split-list lst length)
(define(split-list-head accum length)
(if (= length 0)
(cdr '(accum))
(cons (car accum) (split-list-head (cdr accum)(- length 1)))
)
)
(define(split-list-tail accum length)
(if (= length 0)
(cons (car accum)(cdr accum))
(split-list-tail (cdr accum)(- length 1))
)
)
(if (eq? length 0)
(append(list (list))(list lst))
(append(list(split-list-head lst length)) (list(split-list-tail lst length)))
)
)
Unless you are particularly attached to GNU Scheme, I would consider moving to Dr Racket.
Although it was written for a similar language called Racket, it can be set up to run vanilla Scheme, by putting in a first line #lang scheme
The nice about Dr Racket is that it has a very nice debugger.
My code, with the #lang line at the start, and the erroring line at the bottom:
#lang scheme
(define (split-list lst length)
(define(split-list-head accum length)
(if (= length 0)
(cdr '(accum))
(cons (car accum) (split-list-head (cdr accum)(- length 1)))
)
)
(define(split-list-tail accum length)
(if (= length 0)
(cons (car accum)(cdr accum))
(split-list-tail (cdr accum)(- length 1))
)
)
(if (eq? length 0)
(append(list (list))(list lst))
(append(list(split-list-head lst length)) (list(split-list-tail lst length)))
)
)
(split-list '(a b c d e f g) 7)
If I just run the code, it highlights the error in split-list-tail, where car causes a contract violation. It also shows the call sequence.
That's probably enough to identify the fault, but I can also run the debugger. By clicking on the Debug button I move to the debug mode. By moving the mouse pointer over a parenthesis, and right clicking, I can enable or disable a pause at this point - show by a pink circle. The variables are shown on the right hand side. When I run the code in the debugger, variable accum is empty, hence car accum fails.
My suggestion is that you use pair? or null? to test accum before calling car on it.
Try this. It makes use of three accumulating parameters. A subtraction is also kind of accumulation.
(define (split n xs k)
(define (loop xs n k)
(if
(and (> n 0) (not (null? xs)))
(loop (cdr xs) (- n 1)
(lambda (a b) (k (cons (car xs) a) b)))
(k '() xs)))
(loop xs n k))
Can you see how it is to be called?
Can you explain how it works?
Or a bit shorter,
(define (split n xs k)
(define ((+ f a) b) (f (cons (car a) b)))
(define (loop xs n k)
(if
(and (> n 0) (not (null? xs)))
(loop (cdr xs) (- n 1) (+ k xs))
((k '()) xs)))
(loop xs n k))
Can you find a way how should this function be called? I'll give you a hint, how should this function
(define ((add a) b) (list a b))
be called?
How do I recursively merge jumping pairs of elements of a list of lists? I need to have
'((a b c) (e d f) (g h i))
from
'((a b) c (e d) f (g h) i)
My attempt
(define (f lst)
(if (or (null? lst)
(null? (cdr lst)))
'()
(cons (append (car lst) (list (cadr lst)))
(list (append (caddr lst) (cdddr lst))))))
works if I define
(define listi '((a b) c (d e) f))
from which I obtain
((a b c) (d e f))
by doing simply
(f listi)
but it does not work for longer lists. I know I need recursion but I don't know where to insert f again in the last sentence of my code.
A simpler case that your algorithm fails: (f '((1 2) 3)) should result in '((1 2 3)), but yours results in an error.
We will define some terms first:
An "element" is a regular element, like 1 or 'a.
A "plain list" is simply a list of "element"s with no nested list.
E.g., '(1 2 3) is a plain list. '((1 2) 3) is not a plain list.
A "plain list" is either:
an empty list
a cons of an "element" and the next "plain list"
A "list of jumping pairs" is a list of even length where the odd index has a "plain list", and the even index has an element. E.g., '((1) 2 (a) 4) is a "list of jumping pairs". A "list of jumping pairs" is either:
an empty list
a cons of
a "plain list"
a cons of an "element" and the next "list of jumping pairs"
We are done with terminology. Before writing the function, let's start with some examples:
(f '()) equivalent to (f empty)
should output '()
equivalent to empty
(f '((1 2) 3)) equivalent to (f (cons (cons 1 (cons 2 empty))
(cons 3
empty)))
should output '((1 2 3))
equivalent to (cons (cons 1 (cons 2 (cons 3 empty)))
empty)
(f '((1 2) 3 (4) a)) equivalent to (f (cons (cons 1 (cons 2 empty))
(cons 3
(cons (cons 4 empty)
(cons 'a
empty)))))
should output '((1 2 3) (4 a))
equivalent to (cons (cons 1 (cons 2 (cons 3 empty)))
(cons (cons 4 (cons 'a empty))
empty))
So, f is a function that consumes a "list of jumping pairs" and returns a list of "plain list".
Now we will write the function f:
(define (f lst)
???)
Note that the type of lst is a "list of jumping pairs", so we will perform a case analysis on it straightforwardly:
(define (f lst)
(cond
[(empty? lst) ???] ;; the empty list case
[else ??? ;; the cons case has
(first lst) ;; the "plain list",
(first (rest lst)) ;; the "element", and
(rest (rest lst)) ;; the next "list of jumping pairs"
???])) ;; that are available for us to use
From the example:
(f '()) equivalent to (f empty)
should output '()
equivalent to empty
we know that the empty case should return an empty list, so let's fill in the hole accordingly:
(define (f lst)
(cond
[(empty? lst) empty] ;; the empty list case
[else ??? ;; the cons case has
(first lst) ;; the "plain list",
(first (rest lst)) ;; the "element", and
(rest (rest lst)) ;; the next "list of jumping pairs"
???])) ;; that are available for us to use
From the example:
(f '((1 2) 3)) equivalent to (f (cons (cons 1 (cons 2 empty))
(cons 3
empty)))
should output '((1 2 3))
equivalent to (cons (cons 1 (cons 2 (cons 3 empty)))
empty)
we know that we definitely want to put the "element" into the back of the "plain list" to obtain the resulting "plain list" that we want:
(define (f lst)
(cond
[(empty? lst) empty] ;; the empty list case
[else ;; the cons case has:
???
;; the resulting "plain list" that we want
(append (first lst) (cons (first (rest lst)) empty))
;; the next "list of jumping pairs"
(rest (rest lst))
;; that are available for us to use
???]))
There's still the next "list of jumping pairs" left that we need to deal with, but we have a way to deal with it already: f!
(define (f lst)
(cond
[(empty? lst) empty] ;; the empty list case
[else ;; the cons case has:
???
;; the resulting "plain list" that we want
(append (first lst) (cons (first (rest lst)) empty))
;; the list of "plain list"
(f (rest (rest lst)))
;; that are available for us to use
???]))
And then we can return the answer:
(define (f lst)
(cond
[(empty? lst) empty] ;; the empty list case
[else ;; the cons case returns
;; the resulting list of "plain list" that we want
(cons (append (first lst) (cons (first (rest lst)) empty))
(f (rest (rest lst))))]))
Pattern matching (using match below) is insanely useful for this kind of problem -
(define (f xs)
(match xs
;; '((a b) c . rest)
[(list (list a b) c rest ...)
(cons (list a b c)
(f rest))]
;; otherwise
[_
empty]))
define/match offers some syntax sugar for this common procedure style making things even nicer -
(define/match (f xs)
[((list (list a b) c rest ...))
(cons (list a b c)
(f rest))]
[(_)
empty])
And a tail-recursive revision -
(define (f xs)
(define/match (loop acc xs)
[(acc (list (list a b) c rest ...))
(loop (cons (list a b c) acc)
rest)]
[(acc _)
acc])
(reverse (loop empty xs)))
Output for each program is the same -
(f '((a b) c (e d) f (g h) i))
;; '((a b c) (e d f) (g h i))
(f '((a b) c))
;; '((a b c))
(f '((a b) c x y z))
;; '((a b c))
(f '(x y z))
;; '()
(f '())
;; '()
As an added bonus, this answer does not use the costly append operation
There is no recursive case in your code so it will just work statically for a 4 element list. You need to support the following:
(f '()) ; ==> ()
(f '((a b c) d (e f g) h)) ; ==> (cons (append '(a b c) (list 'd)) (f '((e f g) h)))
Now this requires exactly even number of elements and that every odd element is a proper list. There is nothing wrong with that, but onw might want to ensure this by type checking or by adding code for what should happen when it isn't.
I want to fix my own function that gives the same result with the default intersection function. I've been trying to write a lisp code which prints same elements in the two lists. My code works for it. But it doesn't work for nested lists. How can I fix this?
(defun printelems (L1 L2)
(cond
((null L1) nil) ((member (first L1) L2) (cons (first L1) (printelems (rest L1) L2)))
(t (printelems (rest L1) L2))))
Expected inputs and outputs
(printelems '(2 3 5 7) '( 2 3)) => It works
=> (2 3)
(printelems '(a b '(c f)) '(a d '(c f) e)) => It doesn't work.
=> (a (c f))
Edit
Using the default intersection function works as intended. How can I use the equal function in my recursive function?
For default intersection,
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
((C F) A)
(intersection '(a b (c f)) '(a d c f e) :test 'equal)
(A)
My intersection,
(printelems '(a b (c f)) '(a d c f e))
(A C F)
(printelems '(a b (c f)) '(a d (c f) e) )
(A C F)
My edited code:
(defun flatten (l)
(cond ((null l) nil)
((atom (car l)) (cons (car l) (flatten (cdr l))))
(t (append (flatten (car l)) (flatten (cdr l))))))
(defun printelemsv1(list1 list2)
(cond
((null list1) nil)
(((member (first list1) list2) (cons (first list1) (printelemsv1 (rest list1) list2)))
(t (printelemsv1 (rest list1) list2)))))
(defun printelems (L1 L2)
(printelemsv1 (flatten L1) (flatten L2)))
Common Lisp already has an intersection function. If you want to compare sublists like (C F), you'll want to use equal or equalp as the test argument.
(intersection '(a b '(c f)) '(a d '(c f) e) :test 'equal)
;=> ('(C F) A)
While it doesn't change how intersection works, you probably don't really want quote inside your list. Quote isn't a list creation operator; it's a "return whatever the reader read" operator. The reader can read (a b (c f)) as a list of two symbols and a sublist, so (quote (a b (c f))), usually abbreviated as '(a b (c f)) is fine. E.g.:
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
;=> ((C F) A)
It's always helpful when you provide an example of input and the expected output. I assume you mean you have two lists like '(1 (2 3) 4) and '((1) 2 5 6) that the function should produce '(1 2). In this case you can just flatten the two lists before giving them to printelems.
Since I'm not familiar with Common-Lisp itself I will leave you with one example and a link.
(defun flatten (structure)
(cond ((null structure) nil)
((atom structure) (list structure))
(t (mapcan #'flatten structure))))
Flatten a list - Rosetta Code
flatten takes an arbitrary s-expression like a nested list '(1 (2 3) 4) and returns '(1 2 3 4).
So now you just have to write a new function in which you use your printelems as a helper function and give it flattened lists.
(defun printelems.v2 (L1 L2)
(printelems (flatten L1) (flatten L2)))
Take this with a grain of salt, since as said before I'm not familiar with Common-Lisp, so appologies in advance for any potential syntax errors.
I don't know how I can append an element in n position in a list.
For example:
(insert-at new k lis)
(insert-at ’N 2 ’(a b c d e f))
=>
’(a b N c d e f)
It is ok?:
(define (insert-at new k lis)
(cond (( null? lis)
(list new))
(zero? k
(cons new lis))
(else
(cons (car lis)
(insert-at new (- k 1) (cdr lis))))))
I'll give you some hints - because this looks like homework, I can't give you a straight answer, and it'll be much more useful if you arrive at the solution by your own means. Fill-in the blanks:
(define (insert-at new k lis)
(cond (<???> ; if the list is empty
<???>) ; return a list with the single element `new`
(<???> ; if `k` is zero
<???>) ; cons `new` with the list
(else ; otherwise
(cons <???> ; cons the lists' current element and
(insert-at new <???> <???>))))) ; advance the recursion
Notice that here, "advancing the recursion" means passing the rest of the list and decrementing the k index by one unit. We're done once the k index is zero or the list's end is reached. Don't forget to test the procedure:
(insert-at 'N 2 '(a b c d e f))
=> '(a b N c d e f)
(insert-at 'N 0 '(a b c))
=> '(N a b c)
(insert-at 'N 3 '(a b c))
=> '(a b c N)
If you had two functions:
take-n - which returns as a list the first N elements, and
last-n - which returns as a list the last N elements
then you could write:
(define (insert-at value index list)
(let ((len (length list)))
(assert (<= 0 index len))
(append (take-n index list)
(list value)
(last-n (- len index) list))))
(DEFUN INS-ELEM (Nth item list)
(COND
((< Nth 1) (ERROR "Index too small ~A" Nth))
((= Nth 1) (CONS item list))
((ENDP list) (ERROR "Index too big"))
(T (CONS (FIRST list) (INS-ELEM (1- Nth) item(REST list))))))
Then, just call (INS-ELEM 2 'A '(B C D E F)) and view the result for yourself.
Good luck!
#lang racket
(define (insert-at Index item lst)
(cond
[(< Index 1) (error "Index too small: " Index)]
[(= Index 1) (cons item lst)]
[(> Index (length lst)) (error "Index too big: " Index)]
[else (cons (first lst) (insert-at (- Index 1) item (rest lst)))]))
user3660248
Your idea of how to solve this problem seems right and makes sense, but your implementation of it in Racket was not right and I fixed it and now it works :)
I'll explain in math, here's the transformation I'm struggling to write Scheme code for:
(f '(a b c) '(d e f)) = '(ad (+ bd ae) (+ cd be af) (+ ce bf) cf)
Where two letters together like ad means (* a d).
I'm trying to write it in a purely functional manner, but I'm struggling to see how. Any suggestions would be greatly appreciated.
Here are some examples:
(1mul '(0 1) '(0 1)) = '(0 0 1)
(1mul '(1 2 3) '(1 1)) = '(1 3 5 3)
(1mul '(1 2 3) '(1 2)) = '(1 4 7 6)
(1mul '(1 2 3) '(2 1)) = '(2 5 8 3)
(1mul '(1 2 3) '(2 2)) = '(2 6 10 6)
(1mul '(5 5 5) '(1 1)) = '(5 10 10 5)
(1mul '(0 0 1) '(2 5)) = '(0 0 2 5)
(1mul '(1 1 2 3) '(2 5)) = '(2 7 9 16 15)
So, the pattern is like what I posted at the beginning:
Multiply the first number in the list by every number in the second list (ad, ae, af) and then continue along, (bd, be, bf, cd, ce, cf) and arrange the numbers "somehow" to add the corresponding values. The reason I call it overlapping is because you can sort of visualize it like this:
(list
aa'
(+ ba' ab')
(+ ca' bb' ac')
(+ cb' bc')
cc')
Again,
(f '(a b c) '(d e f)) = '(ad (+ bd ae) (+ cd be af) (+ ce bf) cf)
However, not just for 3x3 lists, for any sized lists.
Here's my code. It's in racket
#lang racket
(define (drop n xs)
(cond [(<= n 0) xs]
[(empty? xs) '()]
[else (drop (sub1 n) (rest xs))]))
(define (take n xs)
(cond [(<= n 0) '()]
[(empty? xs) '()]
[else (cons (first xs) (take (sub1 n) (rest xs)))]))
(define (mult as bs)
(define (*- a b)
(list '* a b))
(define degree (length as))
(append
(for/list ([i (in-range 1 (+ 1 degree))])
(cons '+ (map *- (take i as) (reverse (take i bs)))))
(for/list ([i (in-range 1 degree)])
(cons '+ (map *- (drop i as) (reverse (drop i bs)))))))
The for/lists are just ways of mapping over a list of numbers and collecting the result in a list. If you need, I can reformulate it just maps.
Is this a good candidate for recursion? Not sure, but here's a
a direct translation of what you asked for.
(define (f abc def)
(let ((a (car abc)) (b (cadr abc)) (c (caddr abc))
(d (car def)) (e (cadr def)) (f (caddr def)))
(list (* a d)
(+ (* b d) (* a e))
(+ (* c d) (* b e) (* a f))
(+ (* c e) (* b f))
(* c f))))
Is it correct to assume, that you want to do this computation?
(a+b+c)*(d+e+f) = a(d+e+f) + b(d+e+f) + c(d+e+f)
= ad+ae+af + bd+be+bf + cd+ce+cf
If so, this is simple:
(define (f xs ys)
(* (apply + xs) (apply + ys))
If you are interested in the symbolic version:
#lang racket
(define (f xs ys)
(define (fx x)
(define (fxy y)
(list '* x y))
(cons '+ (map fxy ys)))
(cons '+ (map fx xs)))
And here is a test:
> (f '(a b c) '(d e f))
'(+ (+ (* a d) (* a e) (* a f))
(+ (* b d) (* b e) (* b f))
(+ (* c d) (* c e) (* c f)))