Scheme list as an argument - list

So in Scheme, if I make a list as an argument, how would I go about evaluating that list to itself in the same order?
Would I just write:
(define (function list)
(list)
I don't really understand this.

Your question lacks an example.
Is this what you want:
(define (f . args)
args)
It can be used like this:
> (f 1 2 3)
(1 2 3)

If you have a list and a function which 'evaluates' elements of that list and you want to construct another list which is the result of calling that function on each element of the list then what you are doing is called mapping the function over the list and the function do do that is called map. Given the following two definitions:
(define course-names '((1 "Exploding buckets 101")
(2 "Squirrel cooking 201")
(4 "Flamethrower maintenance 211")))
(define (course->name c)
(let ((found (assq c course-names)))
(if found (second found) "UNKNOWN SECRET COURSE")))
Then
> (map course->name '(1 2 3 4))
'("Exploding buckets 101"
"Squirrel cooking 201"
"UNKNOWN SECRET COURSE"
"Flamethrower maintenance 211")
It's worth seeing how you can write things like map: here is one way:
(define (simple-map f l)
(define (simple-map-loop tail accum)
(if (null? tail)
(reverse accum)
(simple-map-loop (rest tail) (cons (f (first tail)) accum))))
(simple-map-loop l '()))

or:
(define (f lst)
lst)
used as:
(f '(1 2 3))
;; '(1 2 3)

Related

How can I apply each element in a list to a function in scheme?

The function applyToAll is suppose to take in a function and a List, then take the car of the list and apply each element to the fuction.
This is what I have worked out so far:
(define applyToAll(lambda (f L)
(cond
((null? L) '())
(#t (cons (L) (applyToAll f(car L))))
)))
I'm not sure what I am doing wrong. A fuction call would look like
(applyToAll (lambda (n) (* n n)) '(1 2 3) )
and it would return
(1 4 9)
Instead it returns: function call: expected a function after the open parenthesis, but received (list 1 2 3)
Any help as to why my code is not working?
Thanks
It sounds like you are trying to implement map.
The error you are getting is because you are calling a list as though it's a function (lst1)
( ) this means function call in scheme
You are making the same mistake here:
(#t (cons (L) (applyToAll f(car L))))
the right way to apply is:
(function arg0 arg1 ... argn)
You need to apply f to each element in the list like so:
(cons (f (car L)) (applyToAll f (cdr L))))
OR just use map:
(map proc lst ...+)
gl

How to transform a list into a set in LISP?

I have been trying to transform a linear list into a set but with no avail. Everytime I run this, I get some weird compilation errors like "badly formed lambda" which points to the way I use append. Here is my code:
(defun mem(e l)
(cond
((null l) nil)
((equal e (car l)) t)
((listp (car l)) (mem e (car l)))
(t(mem e (cdr l)))
)
)
(defun st(l k)
(cond
((null l) nil)
(( mem '(car l) 'k) (st (cdr l) k))
((listp (car l)) (st (car l) k))
( t (st (cdr l) (append((car l) k)) ))
(t(mem e (cdr l)))
)
)
EDIT: frankly I just want to remove the duplicates from list l
Prefer Standard Library Functions
EDIT: frankly I just want to remove the duplicates from list l
Common Lisp has a remove-duplicates function. The documentation inclues examples:
Examples:
(remove-duplicates "aBcDAbCd" :test #'char-equal :from-end t) => "aBcD"
(remove-duplicates '(a b c b d d e)) => (A C B D E)
(remove-duplicates '(a b c b d d e) :from-end t) => (A B C D E)
(remove-duplicates '((foo #\a) (bar #\%) (baz #\A))
:test #'char-equal :key #'cadr) => ((BAR #\%) (BAZ #\A))
(remove-duplicates '((foo #\a) (bar #\%) (baz #\A))
:test #'char-equal :key #'cadr :from-end t) => ((FOO #\a) (BAR #\%))
Are you trying to flatten the list too?
From your code for mem, where you do:
((listp (car l)) (mem e (car l)))
it looks like you want your member function to also recurse into sublists. That's a bit questionable, even when working with sets, since sets can traditionally include other sets. E.g., {{3},{4},5} is a set containing 5, the set {3}, and the set {4}. It's not the same as the set {3,4,5}. Your st function also looks like it's trying to recurse into lists, which makes it seem like you want to flatten you lists, too. Again, that's a bit questionable, but if you want to do that, then your conversion to a set would be easier as a "flatten, then remove duplicates" process:
(defun flatten (list)
"Returns a fresh list containing the leaf elements of LIST."
(if (listp list)
(mapcan 'flatten list)
(list list)))
;; CL-USER> (flatten '(1 2 (3 4) 5 ((6))))
;; (1 2 3 4 5 6)
(defun to-set (list)
"Returns a set based on the elements of LIST. The result
is a flat list containing the leaf elements of LIST, but
with any duplicate elements removed."
(delete-duplicates (flatten list)))
;; CL-USER> (to-set '(1 3 (3 4) ((4) 5)))
;; (1 3 4 5)
Notes
I get some weird compilation errors like "badly formed lambda" which points to the way I use append.
Yes, you're trying to call append like: (append((car l) k)). That's actually not a problem for append. Remember, the syntax for a function call in Lisp is (function argument…). That means that you've got:
(append ((car l) k))
<function> <argument1>
But your argument1 is also a function call:
((car l) k )
<function> <argument1>
In Common Lisp, you can't use (car l) as a function. The only thing that can appear for a function is a symbol (e.g., car, append) or a lambda expression (e.g., (lambda (x) (+ x 1)).
You want to call (append (car l) k) instead.
First, CL does not have a set data type.
Lists, however, can be used as sets, you do not need to write any special code for that.
Second, I don't understand what your st function is supposed to do, but I bet that in the second cond clause you should not quote (car l) and k. You should use meaningful names for your functions and avoid abbreviations. As per your explanation in the comment, you should use pushnew instead.
Third, your mem function is quite weird, I am pretty sure you do not mean what you wrote: e is searched along a path in the tree l, not in the list l. As per your explanation in the comment, you should check both car and cdr:
(defun tree-member (tree element &key (test #'eql))
(if (consp tree)
(or (tree-member (car tree) element :test test)
(tree-member (cdr tree) element :test test))
(funcall test element tree)))

Transpose a matrix in racket (list of lists

I got a list of lists in racket and have to transpose them.
(: transpose ((list-of(list-of %a)) -> (list-of (list-of %a))))
(check-expect (transpose (list (list 1 2 3)
(list 4 5 6)))
(list (list 1 4)
(list 2 5)
(list 3 6)))
(define transpose
(lambda (xs)
(cond
((empty? xs)empty)
((pair? xs)(make-pair (make-pair (first(first xs)) (make-pair (first(first(rest xs)))empty)) (transpose (rest(rest xs))))))))
That's my code at the moment.
I think the problem is in the recursive call (correct me if I'm wrong please).
The actual outcome is (list (list 1 4)). The rest seems kinda ignored.
It would really help me, if somebody knows the problem, or has a tip.
The simplest definition of transpose is:
(define (transpose xss)
(apply map list xss))
Why does it work?
(apply map list '((a b) (d e))
= (apply map List '((a b) (d e)) ; use List rather than list
= (map List '(a b) '(d e))
= (list (List 'a 'd) (List 'b e))
= '((a d) (b e))
Here List is spelled with capital letters only to show which list was given by the user and which was produced by map.
Here is a less "clever" solution. It uses that the first column of
a matrix becomes the first row in the transposed matrix.
(define transpose
(lambda (xss)
(cond
[(empty? xss) empty]
[(empty? (first xss)) empty]
[else (define first-column (map first xss))
(define other-columns (map rest xss))
(cons first-column
(transpose other-columns))])))
(define (transpose xss)
(apply map list xss))
If you are, like me, new to Scheme, you'll wonder how the apply map list trick works.
It all boils down to understanding apply and map.
First, apply does its job. It takes a function, some fixed arguments and a list of arguments.
It calls the function with the fixed arguments followed by the flattenned list arguments.
So:
(apply map list '((1 2) (3 4)))
^^^^^^^^^^^^^^-- list of arguments
^^^^ ---------------- a fixed argument
^^^ --------------------- function
evaluates to:
(map list '(1 2) '(3 4))
Note how the list of lists is turned into two lists.
Now map accepts an N-argument function and N lists of equal length. Then it returns a list, where each element is an application of the function.
For example
(map + '(1 2) '(3 4))
evaluates to:
(list (+ 1 3) (+ 2 4))
In the transpose trick the function is simply list, so:
(map list '(1 2) '(3 4))
evaluates to:
(list (list 1 3) (list 2 4))
where the first list constructs a list because map always returns a list and the other two are invocations of the passed list function.
for/list can be used sequentially to create a list of lists with transposed items:
(define (transpose_ lol) ; lol is list of lists
(for/list ((i (length (list-ref lol 0)))) ; loop for length of first inner list
(for/list ((il lol)) ; for each inner list (il)
(list-ref il i)))) ; get its item
Testing:
(transpose_ (list (list 1 2 3)
(list 4 5 6)))
Output:
'((1 4) (2 5) (3 6))
(define (tr ls)
(if (empty? (car ls)) empty
(if (null? ls) empty
(cons (map car ls) (tr (map cdr ls))))))

If you're mapping a function over a list in rackect how can you get a reference to the next element?

If I have a list and I map a lambda function over it how can I get a reference to the next or previous item while processing the current one?
(map (lambda (x) x) '(1 2 3))
How would I reference the previous or next element while processing x?
John McCarthy originally made maplist and it's defined in CL still and predates map(car). It's definition in Scheme would be something like:
(define (maplist fun lst)
(if (null? lst)
'()
(cons (fun lst) (maplist fun (cdr lst)))))
(maplist values '(1 2 3 4)) ; ==> ((1 2 3 4) (2 3 4) (3 4) (4))
It's slightly more difficult to get each element like map but if you need more than the first then it's perfect.
Start with your one list, construct two other lists, one 'shifted' right, and the other 'shifted' left. Like this:
(define (process func x)
(let ((to-front (cons 'front (reverse (cdr (reverse x)))))
(to-rear (append (cdr x) (list 'rear))))
(map func to-front x to-rear)))
Note that the stuff above with reverse is because map expects all lists to have the same length. So when adding to the front, you need to remove one from the tail.
Also, the provided func needs to accept three arguments.
> (process list '(a b c))
((front a b) (a b c) (b c rear))
You can always use map on two zipped lists, i.e.
(import (srfi srfi-1)) ; or use some zip implementation
(define a '(1 2 3 4 5))
(map (lambda (x) x)
(zip a
(append (cdr a) (list (car a)))))
which results in ((1 2) (2 3) (3 4) (4 5) (5 1)).
Of course, the above assumes "periodic" boundary conditions for the lists (you should modify the boundary conditions for your case).
And also you would need to modify the lambda to handle pairs of elements.
For simplicity let's take the case of two elements at a time -- the current and next one. So if you have (list 1 2 3), and a function that takes this and next args, you want it to be called with:
1 2
2 3
3 <some value, let's say 3>
You could write that concisely as:
(map f xs (append (drop xs 1) (list (last xs))))
However the drop and append-ing means that's not the fastest way to do it. Instead you could write a map-slide-pairs function to do it more directly:
#lang racket/base
(require racket/match)
;; map a list as "sliding pairs". For example:
;; (map-slide-pairs cons '(1 2 3)) ==> '((1 . 2)
;; (2 . 3)
;; (3 . 3))
(define (map-slide-pairs f xs #:last-val [last-val #f])
;; Concise implementation:
;; (map f xs (append (drop xs 1) (list (last xs)))))
;; Faster implementation:
(let loop ([xs xs])
(match xs
[(list) (list)]
[(list this) (list (f this (or last-val this)))]
[(list this next more ...) (cons (f this next)
(loop (cons next more)))])))
(module+ test
(require rackunit)
(check-equal? (map-slide-pairs cons '(1 2 3))
'([1 . 2][2 . 3][3 . 3]))
(check-equal? (map-slide-pairs cons '(1 2 3) #:last-val 100)
'([1 . 2][2 . 3][3 . 100])))
Hopefully you can see how to extend this and make a "map-slide-triples" function that would be called with the previous, current, and next elements of the list.

Search in a list with argument

I`m trying to implement a function that given an argument and a list, find that argument in the first element of the pair in a list
Like this:
#lang scheme
(define pairs
(list (cons 1 2) (cons 2 3) (cons 2 4) (cons 3 1) (cons 2 5) (cons 4 4)))
;This try only gets the first element, I need to runs o every pair on pairs
((lambda (lst arg)
(if (equal? (car (first lst)) arg) "DIFF" "EQ"))
pairs 2)
;This try below brings nok for every element, because Its not spliting the pairs
(define (arg) (lambda (x)2))
(map
(lambda (e)
(if (equal? arg (car e)) "ok" "nok"))
pairs)
The idea is simple, I have pair elements, and a given number. I need to see if the first element of the pairs (they are in a list) starts with that number
Thanks in advance
In Racket, this is easy to implement in terms of map. Simply do this:
(define (find-pair lst arg)
(map (lambda (e)
(if (equal? (car e) arg) "ok" "nok"))
lst))
Alternatively, you could do the same "by hand", basically reinventing map. Notice that in Scheme we use explicit recursion to implement looping:
(define (find-pair lst arg)
(cond ((null? lst) '())
((equal? (car (first lst)) arg)
(cons "ok" (find-pair (rest lst) arg)))
(else
(cons "nok" (find-pair (rest lst) arg)))))
Either way, it works as expected:
(find-pair pairs 2)
=> '("nok" "ok" "ok" "nok" "ok" "nok")
(find-pair pairs 7)
=> '("nok" "nok" "nok" "nok" "nok" "nok")
In Scheme, you should usually approach algorithms with a recursive mindset - especially when lists are involved. In your case, if you find the element in the car of the list then you are done; if not, then you've got the same problem on the cdr (rest) of the list. When the list is empty, you've not found the result.
Here is a solution:
(define (find pred list)
(and (not (null? list)) ; no list, #f result
(or (pred (car list)) ; pred on car, #t result
(find pred (cdr list))))) ; otherwise, recurse on cdr
With this your predicate function 'match if car of argument is n' is:
(define (predicate-if-car-is-n n)
(lambda (arg)
(eq? n (car arg))))
The above stretches your understanding; make sure you understand it - it returns a new function that uses n.
With everything together, some examples:
> (find (predicate-if-car-is-n 2) '((1 . 2) (2 . 3) (4 . 5)))
#t
> (find (predicate-if-car-is-n 5) '((1 . 2) (2 . 3) (4 . 5)))
#f