Currying using Scheme - scheme

I have three functions for a practice exam that I am struggling on.
A function that takes a predicate "pred" and a set "x" and returns whether or not the predicate is true for all elements in the set.
What I was trying:
(define (all? pred x)
(lambda (t)
(equal? (pred t) x)))
Since pred t returns the subset of x where the predicate is true, I was trying to compare it to the original set... Which obviously isn't the way to do it.
A function that takes an operation "op" and a set "x" and returns a new set where basically the op function has been mapped to the entire set. Basically the equivalent of map, so you'd think I shouldn't be asking for help on this...
What I am trying:
(define (map op x)
(lambda (t)
(map (op t))))
I must be missing some basic aspect of currying because I feel like these operations should be simple..

So you're trying to do something like andmap
You could define a function that evaluates a list to see wether all their elements are #t values.
(define full-true?
(λ (lst)
(if (empty? lst) #t
(if (car lst) (full-true? (cdr lst))
(car lst)))
))
Then, your main function would be:
(define for-all?
(lambda
(pred lst-of-items)
(full-true? (map (lambda (x) (pred x)) lst-of-items))
))

Related

Implementing sublist? using accumulate in Racket

I need to implement sublist? as a one-liner function that uses accumulate.
It is suppose to return true if set1 is in set2.
Something like this:
(define subset?
(lambda (set1 set2)
(accumulate member? (car set1) (lambda (x) x) set2)))
Honestly I think I'm just confused on how accumulate is suppose to work with member, or if member is even the right choice for the operator.
My accumulate function is:
(define accumulate
(lambda (op base func ls)
(if (null? ls)
base
(op (func (car ls))
(accumulate op base func (cdr ls))))))
and member?:
(define member?
(lambda (item ls)
(cond ((null? ls) #f)
((equal? item (car ls)) #t)
(else (member? item (cdr ls))))))
To give the correct definition of subset? first we must understand how the function accumulate works and the meaning of its parameters.
If we “unfold” the recursive definition, we can see that accumulate applies the binary operator op to all the results of applying func to the elements of list ls. And since the list can be empty, in these cases the function is defined to give back the value base.
So, for instance, assuming the recursive execution of the function, the following expression
(accumulate + 0 sqr '(1 2 3))
produces 14, since it is equivalent to:
(+ (sqr 1) (+ (sqr 2) (+ (sqr 3) 0)))
that is 1 + 4 + 9 + 0.
To solve your problem, you have to define a call to accumulate that applies the same operator to a list of elements and then combine the results. In you case, the operation to be applied is a test if an element is member of a list (member?), and you can apply it to all the elements of set1. And you should know, from the definition of the subset, that a set s1 is subset of another set s2 if and only if all the elements of s1 are contained in s2. So the operator that must be applied to combine all the results of the test is just the and boolean operator, so that it will be true if all the elements of s1 are member of s2 and false otherwise. The last thing to decide is the base value: this should be true, since an empty set is always contained in another set.
So this is a possible definition of subset?:
(define (subset? set1 set2)
(accumulate
(lambda (x y) (and x y)) ;; the combination operator
#t ;; the value for the empty list
(lambda(x) (member x set2)) ;; the function to be applied to all the elements of
set1)) ;; the set set1

Scheme Switch-Statement Syntax

What is the smartest way to create a switch statement in Scheme?
I want to check one value up against several others, if one results true the entire function should result true, otherwise false. I am not very good with the syntax in scheme.
In Scheme you have case:
(case (car '(c d))
((a e i o u) 'vowel)
((w y) 'semivowel)
(else 'consonant)) ; ==> consonant
As you see it compares against literal data. Thus you cannot compare the value with other variables. Then you need cond
An alternative to an explicit comparison agains each value, is to use member:
> (define (vowel? x) (member x '(a e i o u))
> (vowel? 'b)
#f
Base Case
Often if you want to return a boolean value a simple boolean expression will be enough. In the simple case several checks within an or will be enough:
(define (switch val)
(or (equal? val 'some-value)
(equal? val 'some-other-value)
(equal? val 'yet-another-value)))
Higher Order Function
Is we're doing this often it's a lot of work, so we can make a function called make-switch that takes a list of values and returns a function that serves as a switch statement for those values:
(define (make-switch list-of-vals)
(define (custom-switch val)
(define (inner vals)
(cond ((null? vals) #f)
((equal? val (first vals)) #t)
(else
(inner (rest vals)))))
(inner list-of-vals))
Then we can use make-switch like this:
> (define k (make-switch '(1 2 a "b")))
> (k 1)
#t
> (k 5)
#f
> (k "a")
#f
> (k "b")
#t
Faster Lookups
If we're mostly checking against a static set of values, then a hash-table is another alternative. This code in #lang racket shows the general approach, an R5RS Scheme could use SRFI-69:
#lang racket
(define (make-switch alist)
(define (list->hash alist)
(make-hash (map (lambda (x) (cons x x))
alist)))
(lambda (val)
(if (hash-ref (list->hash alist) val #f)
#t
#f)))
Note
There may be cases where you want to use eq? or some other test for equality, but I've left make-custom-make-switch as an exercise for further exploration.

All: A Function Returning True if and only if All Elements of a List are True

I am looking for a built-in function in Racket that will return True iff all the items in a list are true.
I tried:
(define (all lst)
(when
(equal? lst '())
#t)
(if (not (car lst))
#f
(all (cdr lst))))
Giving error:
car: contract violation
expected: pair?
given: '()
A couple of testcases:
(all '(#t #f #t)) ; #f
(all '(#t #t #t)) ; #t
Could you please either fix it or point me to the built-in function?
(I googled, but got no meaningful result)
You've already accepted another answer that explains a nice way to do this, but I think it's worth pointing out what was wrong in your attempt, because it was actually very close. The problem is that true from the when block is completely ignored. It doesn't cause the function to return. So even when you have the empty list, you evaluate the when, and then keep on going into the other part where you call car and cdr with the same empty list:
(define (all lst)
(when ; The whole (when ...) expression
(equal? lst '()) ; is evaluated, and then its result
#t) ; is ignored.
(if (not (car lst))
#f
(all (cdr lst))))
A very quick solution would be to change it to:
(define (all lst)
(if (equal? lst '())
#t
(if (not (car lst))
#f
(all (cdr lst)))))
At that point, you can simplify a little bit by using boolean operators rather than returning true and false explicitly, and clean up a little bit by using empty?, as noted in the other answer:
(define (all lst)
(or (empty? lst)
(and (car lst)
(all (cdr lst)))))
You were actually very close at the start.
If you're looking for a builtin solution, you'll probably want to take a look at andmap, which applies a predicate over an entire list and ands the results together.
You could use this to implement all very simply.
(define (all lst)
(andmap identity lst))
By using identity from racket/function, all will just use the values in the list as-is. Instead of using identity explicitly, you could also use values, which is just the identity function on single values, so it's a somewhat common idiom in Racket.
There are two kinds of lists: empty ones and pairs.
Therefore we have the following structure:
(define (all xs)
(cond
[(empty? xs) ...]
[(pair? xs) ...]
[else (error 'all "expected a list, got: " xs)]))
Since all elements in the empty list are true, we get:
(define (all xs)
(cond
[(empty? xs) #t]
[(pair? xs) ...]
[else (error 'all "expected a list, got: " xs)]))
If a list begins with a pair, then all elements of the list are true,
if both the first element of the list and the rest of the elements of the list are true:
(define (all xs)
(cond
[(empty? xs) #t]
[(pair? xs) (and (first xs) (all (rest xs)))]
[else (error 'all "expected a list, got: " xs)]))
Note that part of the problem in your program is the use of when.
The result of
(when #t
'foo)
'bar
is 'bar. The construct when is only useful if you are using side effects (such as caused by set! and friends).
All is a higher order folding function. Scheme refers to these as "reductions" and reduce is available in SRFI-1
In Gauche Scheme:
(use srfi-1)
(define (all list-of-x)
(reduce (lambda (x y)
(and x y))
#t
list-of-x))
Will return #f or a value that evaluates to true. For example:
gosh> (all '(1 2 3))
1
If that's OK, then we're done. Otherwise we can always get #t with:
(use srfi-1)
(define (all-2 list-of-x)
(if (reduce (lambda (x y)
(and x y))
#t
list-of-x)
#t
#f))
And then wind up with:
gosh> (all '(1 2 3))
#t

Scheme - How do I return a function?

This function is displaying the correct thing, but how do I make the output of this function another function?
;;generate an Caesar Cipher single word encoders
;;INPUT:a number "n"
;;OUTPUT:a function, whose input=a word, output=encoded word
(define encode-n
(lambda (n);;"n" is the distance, eg. n=3: a->d,b->e,...z->c
(lambda (w);;"w" is the word to be encoded
(if (not (equal? (car w) '()))
(display (vtc (modulo (+ (ctv (car w)) n) 26)) ))
(if (not (equal? (cdr w) '()))
((encode-n n)(cdr w)) )
)))
You're already returning a function as output:
(define encode-n
(lambda (n)
(lambda (w) ; <- here, you're returning a function!
(if (not (equal? (car w) '()))
(display (vtc (modulo (+ (ctv (car w)) n) 26))))
(if (not (equal? (cdr w) '()))
((encode-n n)(cdr w))))))
Perhaps a simpler example will make things clearer. Let's define a procedure called adder that returns a function that adds a number n to whatever argument x is passed:
(define adder
(lambda (n)
(lambda (x)
(+ n x))))
The function adder receives a single parameter called n and returns a new lambda (an anonymous function), for example:
(define add-10 (adder 10))
In the above code we created a function called add-10 that, using adder, returns a new function which I named add-10, which in turn will add 10 to its parameter:
(add-10 32)
=> 42
We can obtain the same result without explicitly naming the returned function:
((adder 10) 32)
=> 42
There are other equivalent ways to write adder, maybe this syntax will be easier to understand:
(define (adder n)
(lambda (x)
(+ n x)))
Some interpreters allow an even shorter syntax that does exactly the same thing:
(define ((adder n) x)
(+ n x))
I just demonstrated examples of currying and partial application - two related but different concepts, make sure you understand them and don't let the syntax confound you.

Using a list of functions and map (Scheme)

I have to create a function in Scheme that takes in a value X, a list of functions, and returns a list of X's applied to those functions. For example:
(f1 f2 ... fn) and x ==> ((f1 x) (f2 x) ... (fn x))
I'm able to use map to do this. I know how to apply a list of functions to another list:
(define (myMap f_list lst)
(if (null? f_list) lst
(map (car f_list)
(myMap (cdr f_list) lst))))
Is there anyway to alter this to allow me what I need?
you mean like this?
(define (applyAllTo fns x)
(map (lambda (fn) (fn x)) fns))
then
(applyAllTo (list (lambda (x) (* 2 x)) (lambda (x) (* 3 x))) 5)
==> (10 15)
you write:
create a function in Scheme that takes in a value X, a list of functions, and returns a list of X's applied to those functions.
First of all the function that you show isn't quite right:
(define (myMap f_list lst)
(if (null? f_list)
lst
really? return the 2nd argument if the 1st is an empty list? And if the 1st argument is a list of functions - judging from its name - why the 2nd is also called lst? Shouldn't it be x? And if it is, do we really want it returned when the list of functions is empty? No, when the list of functions is empty, there's nothing to apply our value to, so the overall list of results of applying x to each function in the list is ... an empty list, right? So,
(define (myMap f_list x)
the order of arguments is not important. You can change it later.
(if (null? f_list)
'()
(cons ; construct new list node
here you had map. Why? We're defining our own map-like function here. map-like functions construct an output list node by node, from results produced in a certain way from the values in the input list, node by node. I.e. we access the input list node by node, and construct the list of results node by node. Using the cons function .
( .... (car f_list) .... ) ; something to do with car
cons that on top of
(myMap (cdr f_list) x) )))
this part is right. So what do we do with the car of f_list? What is it? A function to be called. So we just call it - apply x to it. The function application syntax in Scheme is just (function argument_value). That's it.
Now you can do even more than what was asked in the assignment. For example, you can write a function that will apply each function in the input list twice to the given argument. It's easy to do, following the same general code skeleton:
(define (maplike_func a_list param) ; args order non-important
(if (null? a_list)
'()
(cons (do_something (car a_list) param)
(maplike_func (cdr a_list) param))))
In fact this skeleton is an instance of another, even more general pattern of folding:
(define (right_fold do_what on_null a_list)
(if (null? a_list)
on_null
(do_what (car a_list)
(lambda () (right_fold do_what on_null (cdr a_list))))))
With it, our function can be expressed as
(define (myMap f_list x)
(right_fold
(lambda (a r) (cons (a x) (r)))
'()
f_list))

Resources