I'm supposed to define the function n! (N-Factorial). The thing is I don't know how to.
Here is what I have so far, can someone please help with this? I don't understand the conditionals in Racket, so an explanation would be great!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
You'll have to take a good look at the documentation first, this is a very simple example but you have to understand the basics before attempting a solution, and make sure you know how to write a recursive procedure. Some comments:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
Notice that the last expression is incorrect, I don't know what it's supposed to do, but as it is it'll raise an error. Delete it, and concentrate on writing the body of the conditional.
The trick with scheme (or lisp) is to understand each little bit between each set of brackets as you build them up into more complex forms.
So lets start with the conditionals. if takes 3 arguments. It evaluates the first, and if that's true, if returns the second, and if the first argument is false it returns the third.
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond would work too - you can read the racket introduction to conditionals here: http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
You can define functions in two different ways. You're using the anonymous function approach, which is fine, but you don't need a lambda in this case, so the simpler syntax is:
(define (function-name arguments) result)
For example:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
Using a lambda like you have achieves the same thing, using different syntax (don't worry about any other differences for now):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
By the way - that '*' is just another character in that name, nothing special (see http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29). A '!' at the end of a function name often means that that function has side effects, but n! is a fine name for your function in this case.
So lets go back to your original question and put the function definition and conditional together. We'll use the "recurrence relation" from the wiki definition because it makes for a nice recursive function: If n is less than 1, then the factorial is 1. Otherwise, the factorial is n times the factorial of one less than n. In code, that looks like:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
That last clause is a little denser than I'd like, so lets just work though it down for n = 2:
(define n 2)
(* n (n! (- n 1)))
; =>
(* 2 (n! (- 2 1)))
(* 2 (n! 1))
(* 2 1)
2
Also, if you're using Racket, it's really easy to confirm that it's working as we expect:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)
Related
I am very new to scheme, and I am having trouble getting simple cond functions that I make to print in DrRacket ide. When I run these two functions:
(define (test x)
(cond
[(zero? x) (error "doesn't get here, either")]
[(positive? x) 'here]))
(define (compare x y)
(cond [(equal? x y) "Is Equal"]))
it prints:
> test 12
#<procedure:test>
12
> compare 12 12
#<procedure:compare>
12
12
Why will it not output any of the errors, or "Is Equal"? It works fine if I run the cond statements directly and replace the variables.
You're not actually calling the new procedures, you must surround the procedure name and its arguments between brackets (), just as you did with all the other procedures you're using in your solution! This is the way:
(test 12)
=> 'here
(compare 12 12)
=> "Is Equal"
does anybody know how can I create a function in Scheme that takes no arguments and everytime I call it returns 0 or 1, depending on how many times it's been called? For example, the 1st time returns 1, the 2nd 0, the 3rd 1, etc.
I suppose I have to use a local variable inside the function, but I don't know exactly how, so that it changes value everytime I call it.
You didn't say how you are calling your function. Did you define some named function as the lambda you return with you make-flip function? I guess this is "making closures 101" but it's the first time I've done to my recollection. Anyway, I tried this way and it seemed to work:
(define (make-flipper)
(let ((flip 0))
(lambda ()
(set! flip (if (= flip 0) 1 0))
flip)))
(define doit (make-flipper))
(doit)
(doit)
(doit)
--results in 1, then 0, then 1. I guess you could change the value in the let if you want it to start with 0.
Your code doesn't work because you're overusing parentheses, which makes your code try to call "procedures" that aren't procedures.
Your code,
(define (make-flip)
(let ((x 1))
(lambda ()
((set! x (- 1 x))
(if (= x 0) (1) (0))))))
attempts the procedure calls (0) and (1), and it also tries to "call" the result of the sequence
(set! x (- 1 x))
(if (= x 0) (1) (0)))
(Scheme never ignores any parentheses the way some other languages do.)
If you fix those,
(define (make-flip)
(let ((x 1))
(lambda ()
(set! x (- 1 x))
(if (= x 0) 1 0))))
it works.
The conditional isn't necessary though, you can also say
(define (make-flip)
(let ((x 0))
(lambda ()
(set! x (- 1 x))
x)))
and get the same result.
If you only need one procedure of this kind, you can also do as follows:
(define flip
(let ((x 1))
(lambda ()
(begin0
x
(set! x (- 1 x))))))
Testing:
> (flip)
1
> (flip)
0
> (flip)
1
> (flip)
0
I am trying to make my own length/2 function(which allows you to find the length of a list) in lisp and am having an issue.
If I were to program this in java I would create a global index variable
that = 0
Then in the method I would do
if(list.equal(null))
{
return index;
}
else
{
index++;
return functioname(tail of list) ;
}.
Obviously this is not actual java syntax but I am just trying to relay the logic I want to apply in lisp.
My main issue is that ifs in lisp only allow you to do
if test expression
then do something
else
do something else
while I am trying to do
if test expression
then do something
else
do 2x something
Is there a way I can accomplish this in lisp or is there a better way to go about this problem?
Do it recursively:
len(list):
if list is null
return 0
else
remove first_item from list
return 1 + len(list)
(define (length items)
(if (null? items)
0
(+ 1
(length (cdr items)))))
(length (list 1 2 3))
3
Or use set!:
(define count 0)
(define (length items)
(when (not (null? items))
(set! count (+ count 1))
(length (cdr items))))
(length (list 1 2 3 4 5))
count
5
Scheme has the special operator begin (the Common Lisp equivalent is progn) that lets you group expressions which are executed in sequence, and returns the last one.
(if (null? items)
0
(begin (set! index (+ 1 index))
(my-length (cdr items))
index))
If the if expression returns nil under the false condition, then you can also use when (as in Rahn's answer) which is a bit more compact.
That said, having a global variable, or any variable at all, whose value gets changed (which is the purpose of a variable) is not the Lisp/recursive way of doing things. (Global variables are not a good thing in any language.) Rahn's first example is the only way any experienced Lisp programmer would do it.
In my example above, the (set! index (+ 1 index)) and index)) lines, and the global variable index are completely unnecessary if you add the 1 to the (my-length (cdr items)). If the list is empty, the length is zero; otherwise, the length is 1 + the length of the tail of the list.
This is related to this question: elisp functions as parameters and as return value
(defun avg-damp (n)
'(lambda(x) (/ n 2.0)))
Either
(funcall (avg-damp 6) 10)
or
((avg-damp 6) 10)
They gave errors of Symbol's value as variable is void: n and eval: Invalid function: (avg-damp 6) respectively.
The reason the first form does not work is that n is bound dynamically, not lexically:
(defun avg-damp (n)
(lexical-let ((n n))
(lambda(x) (/ x n))))
(funcall (avg-damp 3) 12)
==> 4
The reason the second form does not work is that Emacs Lisp is, like Common Lisp, a "lisp-2", not a "lisp-1"
I'm learning Clojure and I'm trying to define a function that take a variable number of parameters (a variadic function) and sum them up (yep, just like the + procedure). However, I donĀ“t know how to implement such function
Everything I can do is:
(defn sum [n1, n2] (+ n1 n2))
Of course this function takes two parameteres and two parameters only. Please teach me how to make it accept (and process) an undefined number of parameters.
In general, non-commutative case you can use apply:
(defn sum [& args] (apply + args))
Since addition is commutative, something like this should work too:
(defn sum [& args] (reduce + args))
& causes args to be bound to the remainder of the argument list (in this case the whole list, as there's nothing to the left of &).
Obviously defining sum like that doesn't make sense, since instead of:
(sum a b c d e ...)
you can just write:
(+ a b c d e ....)
Yehoanathan mentions arity overloading but does not provide a direct example. Here's what he's talking about:
(defn special-sum
([] (+ 10 10))
([x] (+ 10 x))
([x y] (+ x y)))
(special-sum) => 20
(special-sum 50) => 60
(special-sum 50 25) => 75
(defn my-sum
([] 0) ; no parameter
([x] x) ; one parameter
([x y] (+ x y)) ; two parameters
([x y & more] ; more than two parameters
(reduce + (my-sum x y) more))
)
defn is a macro that makes defining functions a little simpler.
Clojure supports arity overloading in a single function object,
self-reference, and variable-arity functions using &
From http://clojure.org/functional_programming
(defn sum [& args]
(print "sum of" args ":" (apply + args)))
This takes any number of arguments and add them up.