Define a function "power" that takes two input arguments m and n, and returns m^n. Then, by using the function "power", define a function sum_power that takes two input arguments m and n and returns the sum: (1^n + 2^n + 3^n +.... + m^n).
int first function i calculate power from given arguments in second function a sum powers. But program gives error: Program stack overflow. RESET...
I cant find my error. Function power is correct I checked.
(defun power(m n)
(let ((result 1))
(dotimes (count n result)
(setf result (* m result)))))
(defun sum_power (m n)
(if (= 0 m)
0
(+ (powern m)
(sum_power (1- m) n))))
Ok the problem is your function sum_power when you pass the variable m
the expression (- 1 m) is an infinite loop first time because is for example
for m = 5 first time (- 1 m) => -4 (new m = -4) second time (- 1 m)
=> 5 (new m = 5)
begin again so is a recusive infinite loop, you never arrive to 1 so this is teh case of the overflow
Use instead the build function (1- m) which decreases the value of m, or (- m 1) if you want
So the new funtion will be like this, also this is no tail recursion so for big m and n it will take a lot of time, but for your needs it should work, and this function is better formated, please take of fromatting when writing lisp functions for easy reading
(defun sum_power (m n)
(if (= 1 m)
1
(+ (power n m) (sum_power (1- m) n))
You have a argument order mistake in your sum_power function. The stand lisp function - when given two arguments subtracts the second argument from the first argument that is (- 1 m) will subtract m from one and NOT 1 from m as you probably expected thus your result will be a negative integer and your base case (= 1 m) will never be reached. For you code to work correctly you have to swap the arguments to - thus (- m 1) or you can user the lisp function 1- (1- m) which subtracts one from its only argument thus a corrected version of your code is as follows:
(defun sum_power (m n)
(if (= 1 m)
1
(+ (power m n) (sum_power (1- m) n))))
On a non-related side-note lisp allows a lot more characters in function, variable and macro names than most other languages thus you can use sum-power instead of sum_power, in-fact it is arguably better lisp style to use hyphens to join multiple-word identifier names rather than underscores (as used in C) or camel-back casing (sumPower as used in Java). Secondly closing parenthesis usually are not written on a separate line but are on the same line as the last expression before the closing parentheses, as I have done above in the corrected version. These are merely conventions you may follow them if you wish but you're not obliged to.
Why you don't use higher-order functions and loop macro? I think is more readable that way:
(defun power (n m)
(reduce #'* (loop for x below n collect m))
(defun sum-power (n m)
(reduce #'+ (loop for x from 1 to m collect (power x n)))
Related
I know the algorithm :
(defun Hanoi (n) (if (= n 1) 1 (+ (* 2 Hanoi(- n 1)) 1)))
However, CLISP said
*** - IF: variable HANOI has no value
How could I tweak this? I can't find out the problem.
Here is your code:
(defun Hanoi (n)
(if (= n 1)
1
(+ (* 2 Hanoi (- n 1))
1)))
The error says:
*** - IF: variable HANOI has no value
So, inside the IF you are making a reference to HANOI as a variable, and there is no such variable currently bound at this point. If we look closely, we can see the following expression:
(* 2 Hanoi (- n 1))
This expressions is the application of function * to 3 arguments, namely 2, Hanoi and (- n 1). The second argument, Hanoi, stands for a variable. But there is no such variable defined here (for example, with a let). You are supposed to call the funtion #'Hanoi using the same syntax as you did for multiplication or addition, which is: wrap the function's name in parentheses along with its arguments:
(hanoi (- n 1))
See https://common-lisp.net/documentation for resources about Common Lisp.
You don't call functions as f(x) in Lisp, you call them as (f x) So your recursive call to hanoi needs to be (hanoi (- n 1)).
Define the function iota1(n, m) that takes positive integers n, m with n < m as input, and outputs the list (n,n+1,n+2,...,m)
I've tried switching the code around multiple times but cannot seem to get it to function and display a list the right way
(define (iota1 n m)
(if (eq? n 0)
'()
(append (iota1 (< n m) (+ n 1)) (list n))))
There's a few oddities to the code you provided, which I've formatted for readability:
(define (iota1 n m)
(if (eq? n 0)
'()
(append (iota (< n m) (+ n 1))
(list n))))
The first is that the expression (< n m) evaluates to a boolean value, depending on whether n is less than m or not. When you apply iota to (< n m) in the expression (iota (< n m) (+ n 1)), you are giving iota a boolean value for its first argument instead of a positive integer.
Secondly, the use of append is strange here. When constructing a list in Racket, it's much more common to use the function cons, which takes as arguments a value, and a list, and returns a new list with the value added to the front. For example,
(append '(3) (append '(4) (append '(5) '()))) ==> '(3 4 5)
(cons 3 (cons 4 (cons 5 '()))) ==> '(3 4 5)
It's a good idea to opt for using cons instead of append because it's simpler, and because it is faster, since cons does not traverse the entire list like append does.
Since this sounds a bit like a homework problem, I'll leave you with a "code template" to help you find the answer:
; n : integer
; m : integer
; return value : list of integers
(define (iota1 n m)
(if (> n m) ; base case; no need to do work when n is greater than m
... ; value that goes at the end of the list
(cons ... ; the value we want to add to the front of the list
(iota1 ... ...)))) ; the call to iota, generating the rest of the list
Welcome to the racket world, my version is here:
#lang racket
(define (iota1 n m)
(let loop ([loop_n n]
[result_list '()])
(if (<= loop_n m)
(loop
(add1 loop_n)
(cons loop_n result_list))
(reverse result_list))))
Both code examples are the for the summation formula:
Code example 1
(defund sigma (func n)
(cond ((= n 1)(funcall func 1)
(t (+ (sigma func(1- n))
(funcal func n))))))
Code example 2
(defund sigma(n)
(cond ((= n 1)1)
(t (+ n(sigma func(1- n))))
Both code examples are the for the summation formula
No they do not. While the second sums the numbers, the first calls a function with the number as argument and sums the result.
It would have f(i) instead of just i after the sigma in the mathematical notation. In higher order function lingo it is a term function. Here are some examples using 10:
(sigma (lambda (v) 1) 10) ; ==> 10 in CL I'd use (sigma (constantly 1) 10)
(sigma #'1+ 10) ; ==> 65
(sigma #'identity 10) ; ==> 55
The second would only produce the third example:
(sigma 10) ; ==> 55
PS: Your functions have syntax errors and typos I have just ignored. You'lll need to fix these before it works. The hardest one is perhaps the missing ending parenthesis in the first cond term making the cond only have one term and the second function also passing func, which doesn't make sense since its version only takes one argument.
(defun sum (n)
(if (n<0) 0 n-1) ;; if n<0, add 0. Else add the next smallest.
(sum (n-1)))
So far I come out with something like this but I am not sure how do I declare a variable to store the sum that I would like to return.
Note that you are implementing 1+2+...+m for m = n-1, which admits a simple formula:
(lambda (n)
;; You could inject n-1 on the formula to get n.(n-1)/2
;; (like in Vatine's answer), but here I just decrement
;; the input to show how to modify the local variable
;; and reuse the formula linked above to sum up-to m.
(decf n)
(if (minusp n)
0
(/ (* n (1+ n)) 2)))
An iterative version would work too, there is no need go recursive when doing simple loops:
(lambda (n) (loop :for x :below n :sum x))
Regarding your code:
Space matters1: n<0 is read as a symbol of name "N<0" (upcased by default). The same goes for n-1 which is a symbol named "N-1".
(n<0) will attempt to run the function named n<0. The same goes for (n-1).
Comparison: you can use (minusp n) or (< n 0).
Decrement: you can use (1- n) or (- n 1).
If what you wrote was correctly written, like this:
(defun sum (n)
(if (< n 0) 0 (- n 1))
(sum (- n 1)))
... there would still be issues:
You expect your (n-1) to actually decrement n but here the if only compute a value without doing side-effects.
You unconditionally call (sum (n-1)), which means: infinite recursion. The value returned by the preceding if is always ignored.
1: For details, look at constituent and terminating characters: 2.1.4 Character Syntax Types
Edit: zerop > minusp to check for negative numbers, fixed to fit OPs question
Was some time ago I used Lisp but if I recall right the last evaluation gets returned. A recursive solution to your problem would look like this:
(defun sum (n)
(if (<= n 0) 0 ;;if n is less or equal than 0 return 0
(+ (- n 1) (sum (- n 1))))) ;; else add (n-1) to sum of (n-1)
In Lisp, all comparator functions are just that, functions, so it needs to be (< n 0) and (- n 1) (or, more succinct, (1- n)).
You don't need to keep an intermediate value, you can simply add things up as you go. However, this is complicated by the fact that you are summing to "less than n", not "to n", so you need to use a helper function, if you want to do this recursively.
Even better, if you peruse the standard (easily available on-line, as the Common Lisp HyperSpec, you will sooner or later come across the chapter on iteration, where the loop facility does everything you want.
So if I needed to do this, I would do one of:
(defun my-sum (n)
(/ (* n (1- n)) 2))
or
(defun my-sum (n)
(loop for i below n
sum i))
If I absolutely needed to make it recursive, I would use something like:
(defun my-sum (n)
(labels ((sum-inner (i)
(if (< i 1)
0
(+ i (sum-inner (1- i))))))
(sum-inner (1- n))))
This is (almost) identical to defining a global function called sum-inner, which may be preferable for debugging purposes. However, since it is very unlikely that sum-inner would have any other use, I made it local.
(repeat-transformation #'(lambda (x) (* 2 x)) 4 1)
This is a LISP lambda function , i don't understand what is the last "1" ?
Thanks.
Definition: repeat-transformation (F N X)
Repeat applying function F on object X for N times.
You're defining your lambda function to be called by repeat-transformation 4 times on the integer 1.
Hope that explains it.
Google comes back with a recursive definition for repeat-transformation:
(defun repeat-transformation (F N X)
"Repeat applying function F on object X for N times."
(if (zerop N)
X
(repeat-transformation F (1- N) (funcall F X))))
Which indicates the 1 is the value on which the function operates. The next 3 Google links confirm it.
The lambda function is the first argument to repeat-transformation. 4 and 1 are the second and third arguments respectively.
The Lisp Tutorial Advanced Functional Programming in LISP defines a repeat-transformation function that repeats applying function F on object X for N times. If yours is equivalent, then the 1 is the number of times to apply the lambda function on the value 4.