I want to create a function : OP from i=n to p = f(i)
OP is a binary operator
Here is my function
(defun sigmaOP (f o n p)
(loop for i from n to p do
(let (val (o (val (funcall f i))))
)
val
)
f is a function
o is the operator
n is the begining and p the end
And to call I use
(sigmaOP (lambda (x) (* 2 x)) '+ 1 3)
But it doesn't work
The o argument isn't consider as operator.
This function work if I remove o and instead there is + or *,...
Thanks
An operator is a function to call, too, so you need to precede o with funcall, or use it as a parameter in a call e.g. to reduce. Are you thinking of something like this?
(defun sigmaOP (f o n p)
(reduce o
(loop for i from n to p
collect (funcall f i))))
Call:
(sigmaOP (lambda (x) (* 2 x)) #'+ 1 3)
Related
I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Edit: I've only figured out how to use the for loop but I'm not entirely sure if there's a specific function I can use to only show every 3rd number. I feel like I might be on the right path when using car/cdr function except I'm getting an error
rest: contract violation
expected: (and/c list? (not/c empty?))
given: 0
My code:
(for/list ([x (in-range 20)] #:when (car(cdr(cdr x)))) (displayln x))
I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Typically it is more useful to create a new list with the desired values, and then print those values, or pass them to a function, or do whatever else may be needed. for/list does indeed return a list, and this is one reason for problems encountered by OP example code. (Other problems in OP code include that x is a number with [x (in-range 20)], so (cdr x) is not defined).
A possible solution would be to recurse over the input list, using take to grab the next three values, keeping the third, and using drop to reduce the input list:
;; Recurse using `take` and `drop`:
(define (every-3rd-1 lst)
(if (< (length lst) 3)
'()
(cons (third (take lst 3))
(every-3rd-1 (drop lst 3)))))
Another option would be to recurse on the input list using an auxiliary counter; starting from 1, only keep the values from the input list when the counter is a multiple of 3:
;; Recurse using an auxilliary counter:
(define (every-3rd-2 lst)
(define (every-3rd-helper lst counter)
(cond [(null? lst)
'()]
[(zero? (remainder counter 3))
(cons (first lst) (every-3rd-helper (rest lst) (add1 counter)))]
[else (every-3rd-helper (rest lst) (add1 counter))]))
(every-3rd-helper lst 1))
Yet another possibility would be to use for/list to build a list; here i is bound to values from the input list, and counter is bound to values from a list of counting numbers:
;; Use `for/list` to build a list:
(define (every-3rd-3 lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter 3)))
i))
This function (or any of them, for that matter) could be usefully generalized to keep every nth element:
;; Generalize to `every-nth`:
(define (every-nth n lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter n)))
i))
Finally, map could be used to create a list containing every nth element by mapping over a range of every nth index into the list:
;; Use `map` and `range`:
(define (every-nth-map n lst)
(map (lambda (x) (list-ref lst x)) (range (sub1 n) (length lst) n)))
If what OP really requires is simply to print every third value, rather than to create a list of every third value, perhaps the code above can provide useful materials allowing OP to come to a satisfactory conclusion. But, each of these functions can be used to print results as OP desires, as well:
scratch.rkt> (for ([x (every-3rd-1 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-2 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth-map 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
Here is a template:
(for ([x (in-list xs)]
[i (in-naturals]
#:when some-condition-involving-i)
(displayln x))
can u pls help me guys, its a tutorial question given to us by our lecturer & we can't actually seem to crack it no matter how much we tried. plz help
; perform some type/error checking,
; then call function h to ....
(defun f (L N)
(cond
( (not (listp L) ) nil)
( (not (integerp N) ) nil)
( (< N 1) nil)
( (< (length L) N) nil)
(t (h L N '() ) )
)
)
(defun h (L N Acc)
(cond
( (eq N 1) (append Acc (cdr L) ) )
(t (h (cdr L) (- N 1) (append Acc (list (car L) ) ) ) )
)
)
For the function call (f '(1 2 3) 1) show the sequence of calls (if any) made to function h, and show the final value returned by function f.
For the function call (f '(1 2 3 4) 3) show the sequence of calls (if any) made to function h, and show the final value returned by function f.
If we observe that function f appears to carry out some basic type/error checking and then calls function h to do the "real" work, what is it that h actually accomplishes?
General remarks
You cannot assume EQ will work reliably with numbers, according to the specification. Since N is a number, you should use = instead.
The COND in H has only two possible outcomes; that may be rewritten with an IF.
Do not add spaces between parentheses, do not let parentheses alone on a line. Please follow the usual formatting of Lisp forms (see for example http://lisp-lang.org/style-guide).
The overuse of APPEND in H is making the code more complex than it should be.
Function F
(defun f (L N)
(cond
( (not (listp L) ) nil)
( (not (integerp N) ) nil)
( (< N 1) nil)
( (< (length L) N) nil)
(t (h L N '() ) )
)
)
Function F calls H only when the code reaches the clauses guarded by T, which happens only when all the previous test fails.
Let's invert all tests to simplify a little bit, and use WHEN.
The equivalent form is:
(defun f (list number)
(when (and (listp list)
(integerp number)
(<= 1 number (length list)))
(h list number)))
The third argument to h is omitted, because we do not need it.
Function H
(defun h (L N Acc)
(cond
( (eq N 1) (append Acc (cdr L) ) )
(t (h (cdr L) (- N 1) (append Acc (list (car L) ) ) ) )
)
)
The code is using APPEND at each step of recursion. The accumulator might have been added to make the function tail-recursive, or maybe just to obfuscate the intent. You could rewrite H without the auxiliary list to better understand what it does:
(defun h (list number)
(if (= number 1)
(cdr list)
(cons (car list)
(h (cdr list) (- number 1)))))
And some tests:
(f '(a b c d e f) 3)
=> (A B D E F)
(f '(a b c d e f) 2)
=> (A C D E F)
;; compute the max of a list of integers
(define Y
(lambda (w)
((lambda (f)
(f f))
(lambda (f)
(w (lambda (x)
((f f) x)))))))
((Y
(lambda (max)
(lambda (l)
(cond ((null? l) -1)
((> (car l) (max (cdr l))) (car l))
(else (max (cdr l)))))))
'(1 2 3 4 5))
I wish to understand this construction. Can somebody give a clear and simple explanation for this code?
For example, supposing that I forget the formula of Y. How can I remember it , and reproduce it long after I work with it ?
Here's some related answers (by me):
Y combinator discussion in "The Little Schemer"
Unable to get implementation of Y combinator working
In Scheme, how do you use lambda to create a recursive function?
Basically, with Y defined as λr.(λh.h h) (λg.r (λx.(g g) x)), an application Y r reduces as
Y r
(λw.(λh.h h) (λg.w (λx.(g g) x))) r
(λh.h h) (λg.r (λx.(g g) x))
h h
;where
h = (λg.r (λx.(g g) x)) <----\
|
(λg.r (λx.(g g) x)) h |
r (λx.(g g) x) <-------------- | ----------\
;where | |
g = h -----/ |
;so that |
(g g) = (h h) = r (λx.(g g) x) ------/
So r must expect two arguments - first representing the recursive function to be called, and second - an actual argument:
r = λf (λx. ....x.....(f y)...... )
so that (Y r) x reduces as
(r (λx.(g g) x)) x
(r f) x
;where
f = (λx.(g g) x)
f y = (λx.(g g) x) y = (g g) y = (r f) y ; f is "fixed point" of r
The definiton f = (λx.(g g) x) means, when f y is called, (g g) y will be called, at which point g will be self-applied, r "pulled" from inside g and the result of (r f) called with y argument. I.e. any call (f y) in the body of lambda expression resulting from (r f) application, is translated back to (r f) y i.e. invocation of same body with a new argument y.
The important implementational detail is whether it is the same function body, or its copy, but the semantics are the same - we are able to enter the same function body with a new argument value.
The essence of Y combinator is replication through reference and self-application: we refer to the same thing through same name, twice; and thus we arrange for it to receive itself as an argument.
When there's no referencing, as in pure lambda calculus, and parameters receive textual copies of arguments - i.e. reduction is done by textual rewriting - this still works, because same copies get replicated and passed around, being fed as argument to self so it is available on the next iteration, if need be.
But it is much more efficient when shared referencing is available (all uses of same name refer to same thing). Under environment model of evaluation creation of self-referential function is simple as
(let ((fact #f))
(set! fact
(lambda (n) (if (< 2 n) 1
(* n (fact (- n 1))))))
fact)
In fact the definition in your answer is that of applicative-order Y combinator. With normal-order, eta-reduction can be applied without causing infinite looping, to get Ynorm = (λw.(λh.h h) (λg.w (g g))) which is canonically written as
Ynorm = (λf.(λx.f (x x)) (λx.f (x x)))
indeed
Ynorm g
= (λx.g (x x)) (λx.g (x x))
= g ((λx.g (x x)) (λx.g (x x)))
Im new to Scheme and trying to make function that is (in f u x), u is integer, x is a list and f binary function. The scheme expression (in + 3 '(1 2 3)) should return 3+1+2+3=9.
I have this but if i do (in + 3 '(1 2)) it return 3 not 6. What am i doing wrong?
(define (in f u x)
(define (h x u)
(if (null? x)
u
(h (cdr x) (f u (car x)))))
(h x 0))
From what I understand of what your in function is supposed to do, you can define it this way:
(define in fold) ; after loading SRFI 1
:-P
(More seriously, you can look at my implementation of fold for some ideas, but you should submit your own version for homework.)
(define (repeated f n)
if (= n 0)
f
((compose repeated f) (lambda (x) (- n 1))))
I wrote this function, but how would I express this more clearly, using simple recursion with repeated?
I'm sorry, I forgot to define my compose function.
(define (compose f g) (lambda (x) (f (g x))))
And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.
I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated can be written as follows:
(define (repeated f n)
(lambda (x)
(if (= n 0)
x
((repeated f (- n 1)) (f x)))))
(define (square x)
(* x x))
(define y (repeated square 3))
(y 2) ; returns 256, which is (square (square (square 2)))
(define (repeated f n)
(lambda (x)
(let recur ((x x) (n n))
(if (= n 0)
args
(recur (f x) (sub1 n))))))
Write the function the way you normally would, except that the arguments are passed in two stages. It might be even clearer to define repeated this way:
(define repeated (lambda (f n) (lambda (x)
(define (recur x n)
(if (= n 0)
x
(recur (f x) (sub1 n))))
(recur x n))))
You don't have to use a 'let-loop' this way, and the lambdas make it obvious that you expect your arguments in two stages.
(Note:recur is not built in to Scheme as it is in Clojure, I just like the name)
> (define foonly (repeat sub1 10))
> (foonly 11)
1
> (foonly 9)
-1
The cool functional feature you want here is currying, not composition. Here's the Haskell with implicit currying:
repeated _ 0 x = x
repeated f n x = repeated f (pred n) (f x)
I hope this isn't a homework problem.
What is your function trying to do, just out of curiosity? Is it to run f, n times? If so, you can do this.
(define (repeated f n)
(for-each (lambda (i) (f)) (iota n)))