How to pass on a lambda that produces a list to a procedure that expects a list? - functional-programming

I have the following procedures:
(define (remove-first f)
(rest f))
(define (sty f)
(remove-first (lambda (x) (map f x))))
(define (square x)
(* x x))
(define new-func (sty square))
(new-func (list 1 2 3))
Here, I want to create a function sty that takes in a function, applies it to a list and then removes the first element of the list. However, when I run it, I get the following error:
rest: expects a non-empty list; given: (lambda (a1) ...)
I understand the error but am not sure how I can pass my lambda (which will produce a list) to remove-first

I will assume that definitions of remove-first, square, new-func and (new-func (list 1 2 3)) are parts of the assignment and you can't change them.
In that case, function sty can't return a list. It has to return closure. Closure is a lambda function that "remembers" variables from the environment, where it was created. So, your function will "remember" the value of f and you just have to call it with the list to get the expected result.
This is a default behaviour of lambda, so you just have to change the order of remove-first and lambda:
(define (remove-first f)
(rest f))
(define (sty f)
(lambda (x) (remove-first (map f x))))
(define (square x)
(* x x))
(define new-func (sty square))
(new-func (list 1 2 3))

What you try to do in sty is actually to compose two functions (chaining them) - the remove-first and your lambda:
(define (remove-first f)
(rest f))
(define (sty f)
(compose remove-first (lambda (x) (map f x)))))
(define (square x)
(* x x))
(define new-func (sty square))
(new-func (list 1 2 3)) ;;=> '(4 9)

new-func is supposed to be a function.
So, (sty square) must be a function.
That means that sty must have the form
(define (sty f)
(lambda (x) ...))
Adding "map f over x and remove the first element":
(define (sty f)
(lambda (x) (rest (map f x))))
Note that, unless f has any side effects, it is a waste of work to apply it to the list's head and discard the result, and it makes more sense to throw the head away first:
(define (sty f)
(lambda (x) (map f (rest x))))

Related

Apply a selected function from a list of functions

I want to select from a list of functions. And apply a choosen function to arguments.
(defvar fn '(#'(lambda (x) (* x x)) #'(lambda (x) (+ x x))))
(apply (nth 1 fn) '(5))
Above code does not work what could be wrong?
If you use Lisp one can interactively explore these data structures:
CL-USER 50 > '(#'(lambda (x) (* x x)) #'(lambda (x) (+ x x)))
((FUNCTION (LAMBDA (X) (* X X)))
(FUNCTION (LAMBDA (X) (+ X X))))
Above is a list. What type are the elements:
CL-USER 51 > (mapcar #'type-of *)
(CONS CONS)
Above says that the elements are not functions, but cons cells.
We now evaluate the list elements:
CL-USER 52 > (mapcar #'eval **)
(#<anonymous interpreted function 40600010FC>
#<anonymous interpreted function 406000112C>)
What type are these elements of? Now they are functions:
CL-USER 53 > (mapcar #'type-of *)
(FUNCTION FUNCTION)
fn is not a list of functions. Since you quoted the list, none of the function expressions are evaluated. So you just have a list of lists of the form (FUNCTION (LAMBDA (X) ...)).
Use list to make the list and evaluate all the arguments:
(defvar fn (list #'(lambda (x) (* x x)) #'(lambda (x) (+ x x))))
Or use backquote and comma:
(defvar fn `(,#'(lambda (x) (* x x)) ,#'(lambda (x) (+ x x))))
'(#'(lambda (x) (* x x)) #'(lambda (x) (+ x x)))) is a quoted expression. fn is a list of symbols in your example.
You actually want the lambdas to be evaluated to functions so you would remove the quote and write:
(defvar *fn* (list (lambda (x) (* x x)) (lambda (x) (+ x x))))
Now each function object can indeed be used as argument to apply:
(apply (car *fn*) (list 3))
=> 9
funcall also exists. See if you can understand how it differs from apply by reading the HyperSpec. You would call it like this:
(funcall (cadr *fn*) 3)
=> 6

Counting number of occurrences of elements in a list

I am writing a function called count-if, which takes in a predicate, p?, and a list, ls. The function returns the number of occurrences of elements in the nested list that satisfy p?
For example: (count-if (lambda (x) (eq? 'z x)) '((f x) z (((z x c v z) (y))))) will return 3. This is what I have written:
(define (count-if p ls) (cond
((null? ls) '())
((p (car ls))
(+ 1 (count-if p (cdr ls))))
(else
(count-if p (cdr ls)))))
But I just get an error. I could use some help finding a better way to go about this problem. Thanks!
What is the signature of count-if? It is:
[X] [X -> Boolean] [List-of X] -> Number
What does the first cond clause return? It returns:
'()
This is a simple type error. Just change the base case to 0 and count-if works.
Edit (for nested).
First we define the structure of the date as Nested.
A symbol is just fed into the score helper function. Otherwise the recursive call is applied on all nested sub-nesteds, and the results are summed up.
#lang racket
; Nested is one of:
; - Number
; - [List-of Nested]
; Nested -> Number
(define (count-if pred inp)
; Symbol -> Number
(define (score n) (if (pred n) 1 0))
; Nested -> Number
(define (count-if-h inp)
(if (symbol? inp)
(score inp)
(apply + (map count-if-h inp))))
(count-if-h inp))
(count-if (lambda (x) (eq? 'z x)) '((f x) z (((z x c v z) (y)))))
; => 3

Return a list of procedures that where the function at position k adds k to the input without using cons or list function in scheme? [duplicate]

I'm looking to create a function that returns a list of 'n' functions each of which increments the input by 1, 2, 3... n respectively.
I use DrRacket to try this out. A sample of expected outcome :
> (map (lambda (f) (f 20)) (func-list 5))
(21 22 23 24 25)
I'm able to write this down in a static-way :
> (define (func-list num)
> (list (lambda (x) (+ x 1)) (lambda (x) (+ x 2)) (lambda (x) (+ x 3)) (lambda (x) (+ x 4)) (lambda (x) (+ x 5)))
[Edit]
Also that a few restrictions are placed on implementation :
Only 'cons' and arithmetic operations can be used
The func-list should take as input only one parameter ('n' being the number of functions to be returned in this case)
It would be great if somebody can help me out. Thanks in advance.
Instead of explicitly writing out the list, a better approach would be to recursively construct it for an arbitrary n, as follows:
(define (func-list n)
(define (func-lst a n)
(if (> a n)
empty
(cons (lambda (x) (+ x a))
(func-lst (add1 a) n))))
(func-lst 1 n))
For example:
> (map (lambda (f) (f 20)) (func-list 0))
'()
> (map (lambda (f) (f 20)) (func-list 5))
'(21 22 23 24 25)

passing function as a parameter to another function in scheme

Basicly,what I want to do is this:
I have a function square(x) (define (square x) (* x x))(f(x)=x*x),and another function mul_two (define (mul_two x) (* 2 x))(g(x)=2*x), I want to construct a new function based on the above two functions, what the new function does is this: 2*(x*x)(p(x)=g(f(x))), how can I write this new function in scheme? Although its a pretty straight thing in mathmatical form I'm totally stuck on this .
The usual way to do what you're asking is by using compose, which according to the linked documentation:
Returns a procedure that composes the given functions, applying the last proc first and the first proc last.
Notice that compose is quite powerful, it allows us to pass an arbitrary number of functions that consume and produce any number of values. But your example is simple to implement:
(define (square x) ; f(x)
(* x x))
(define (mul_two x) ; g(x)
(* 2 x))
(define p ; g(f(x))
(compose mul_two square))
(p 3) ; same as (mul_two (square 3))
=> 18
If for some reason your Scheme interpreter doesn't come with a built-in compose, it's easy to code one - and if I understood correctly the comments to the other answer, you want to use currying. Let's write one for the simple case where only a single value is produced/consumed by each function, and only two functions are composed:
(define my-compose ; curried and simplified version of `compose`
(lambda (g)
(lambda (f)
(lambda (x)
(g (f x))))))
(define p ; g(f(x))
((my-compose mul_two) square))
(p 3) ; same as (mul_two (square 3))
=> 18
(define (new_fun x) (mul_two (square x)))
EDIT:
(define (square x) (* x x))
(define (mul_two x) (* 2 x))
(define (new_fun fun1 fun2) (lambda (x) (fun2 (fun1 x))))
((new_fun square mul_two) 10)
And you will get 200. (10 * 10 * 2)
Also, you can implement a general purpose my-compose function just as the compose in racket:
(define (my-compose . funcs)
(let compose2
((func-list (cdr funcs))
(func (lambda args (apply (car funcs) args))))
(if (null? func-list)
func
(compose2
(cdr func-list)
(lambda args (func (apply (car func-list) args)))))))
And you can obtain new-fun by:
(define new-fun (my-compose mul_two square))
In #!racket (the language) you have compose such that:
(define double-square (compose double square))
Which is the same as doing this:
(define (double-square . args)
(double (apply square args)))
If you want to use Scheme (the standard) you can roll your own:
#!r6rs
(import (rnrs))
(define (compose . funs)
(let* ((funs-rev (reverse funs))
(first-fun (car funs-rev))
(chain (cdr funs-rev)))
(lambda args
(fold-left (lambda (arg fun)
(fun arg))
(apply first-fun args)
chain))))
(define add-square (compose (lambda (x) (* x x)) +))
(add-square 2 3 4) ; ==> 81

Scheme/Lisp nested loops and recursion

I'm trying to solve a problem in Scheme which is demanding me to use a nested loop or a nested recursion.
e.g. I have two lists which I have to check a condition on their Cartesian product.
What is the best way to approach these types of problems? Any pointers on how to simplify these types of functions?
I'll elaborate a bit, since my intent might not be clear enough.
A regular recursive function might look like this:
(define (factorial n)
(factorial-impl n 1))
(define (factorial-impl n t)
(if (eq? n 0)
t
(factorial-impl (- n 1) (* t n))))
Trying to write a similar function but with nested recursion introduces a new level of complexity to the code, and I was wondering what the basic pattern is for these types of functions, as it can get very ugly, very fast.
As a specific example, I'm looking for the easiest way to visit all the items in a cartesian product of two lists.
In Scheme,
The "map" function is often handy for computing one list based on another.
In fact, in scheme, map takes an "n-argument" function and "n" lists and calls the
function for each corresponding element of each list:
> (map * '(3 4 5) '(1 2 3))
(3 8 15)
But a very natural addition to this would be a "cartesian-map" function, which would call your "n-argument" function with all of the different ways of picking one element from each list. It took me a while to figure out exactly how to do it, but here you go:
; curry takes:
; * a p-argument function AND
; * n actual arguments,
; and returns a function requiring only (p-n) arguments
; where the first "n" arguments are already bound. A simple
; example
; (define add1 (curry + 1))
; (add1 3)
; => 4
; Many other languages implicitly "curry" whenever you call
; a function with not enough arguments.
(define curry
(lambda (f . c) (lambda x (apply f (append c x)))))
; take a list of tuples and an element, return another list
; with that element stitched on to each of the tuples:
; e.g.
; > (stitch '(1 2 3) 4)
; ((4 . 1) (4 . 2) (4 . 3))
(define stitch
(lambda (tuples element)
(map (curry cons element) tuples)))
; Flatten takes a list of lists and produces a single list
; e.g.
; > (flatten '((1 2) (3 4)))
; (1 2 3 4)
(define flatten
(curry apply append))
; cartesian takes two lists and returns their cartesian product
; e.g.
; > (cartesian '(1 2 3) '(4 5))
; ((1 . 4) (1 . 5) (2 . 4) (2 . 5) (3 . 4) (3 . 5))
(define cartesian
(lambda (l1 l2)
(flatten (map (curry stitch l2) l1))))
; cartesian-lists takes a list of lists
; and returns a single list containing the cartesian product of all of the lists.
; We start with a list containing a single 'nil', so that we create a
; "list of lists" rather than a list of "tuples".
; The other interesting function we use here is "fold-right" (sometimes called
; "foldr" or "reduce" in other implementations). It can be used
; to collapse a list from right to left using some binary operation and an
; initial value.
; e.g.
; (fold-right cons '() '(1 2 3))
; is equivalent to
; ((cons 1 (cons 2 (cons 3 '())))
; In our case, we have a list of lists, and our binary operation is to get the
; "cartesian product" between each list.
(define cartesian-lists
(lambda (lists)
(fold-right cartesian '(()) lists)))
; cartesian-map takes a n-argument function and n lists
; and returns a single list containing the result of calling that
; n-argument function for each combination of elements in the list:
; > (cartesian-map list '(a b) '(c d e) '(f g))
; ((a c f) (a c g) (a d f) (a d g) (a e f) (a e g) (b c f)
; (b c g) (b d f) (b d g) (b e f) (b e g))
(define cartesian-map
(lambda (f . lists)
(map (curry apply f) (cartesian-lists lists))))
Without all the comments and some more compact function definition syntax we have:
(define (curry f . c) (lambda x (apply f (append c x))))
(define (stitch tuples element)
(map (curry cons element) tuples))
(define flatten (curry apply append))
(define (cartesian l1 l2)
(flatten (map (curry stitch l2) l1)))
(define cartesian-lists (curry fold-right cartesian '(()))))
(define (cartesian-map f . lists)
(map (curry apply f) (cartesian-lists lists)))
I thought the above was reasonably "elegant"... until someone showed me the equivalent Haskell definition:
cartes f (a:b:[]) = [ f x y | x <- a , y <- b ]
cartes f (a:b:bs) = cartes f ([ f x y | x <- a , y <- b ]:bs)
2 lines!!!
I am not so confident on the efficiency of my implementation - particularly the "flatten" step was quick to write but could end up calling "append"
with a very large number of lists, which may or may not be very efficient on some Scheme
implementations.
For ultimate practicality/usefulness you would want a version that could take "lazily evaluated" lists/streams/iterator rather than fully specified lists.... a "cartesian-map-stream" function if you like, that would then return a "stream" of the results... but this depends on the context (I am thinking of the "stream" concept as introduced in SICP)... and would come for free from the Haskell version thanks to it's lazy evaluation.
In general, in Scheme, if you wanted to "break out" of the looping at some point you could also use a continuation (like throwing an exception but it is accepted practise in Scheme for control flow).
I had fun writing this!
I'm not sure I see what the problem is.
I believe the main thing you have to understand in functional programming is : build complicated functions by composing several simpler functions.
For instance, in this case:
;compute the list of the (x,y) for y in l
(define (pairs x l)
(define (aux accu x l)
(if (null? l)
accu
(let ((y (car l))
(tail (cdr l)))
(aux (cons (cons x y) accu) x tail))))
(aux '() x l))
(define (cartesian-product l m)
(define (aux accu l)
(if (null? l)
accu
(let ((x (car l))
(tail (cdr l)))
(aux (append (pairs x m) accu) tail))))
(aux '() l))
You identify the different steps: to get the cartesian product, if you "loop" over the first list, you're going to have to be able to compute the list of the (x,y), for y in the second list.
There are some good answers here already, but for simple nested functions (like your tail-recursive factorial), I prefer a named let:
(define factorial
(lambda (n)
(let factorial-impl ([n n] [t 1])
(if (eq? n 0)
t
(factorial-impl (- n 1) (* t n))))))

Resources