I am new to Racket and functional languages in general. For now I am just trying to prepend items to a list. The concepts are a bit confusing and not sure why my code isn't working.
I am trying to do dot product calculations.
I have a function called "dProduct" that takes 2 lists (A and B) and multiplies each corresponding element in them.
;function takes dot product
(define (dProduct A B)
(define C '()) ; define list to store the multiplied elements
;multiply ea lists elements
(for ([i A] [j B])
(display (* i j)) ;THIS WORKS
(cons (* i j) C) ;APPARENTLY DOESN'T WORK
)
;THIS FOR LOOP DISPLAYS NOTHING
;display the new list "C"
(for ([k C])
(display k)
)
)
I don't understand why I can't use cons to prepend the new multiplied elements to my new list "C". What am I missing? Everything compiles fine. Would like to figure this out so I can finish this function :) Any help would be great. Thanks!
Lists are immutable, and cons does not prepend an element to an existing list. Instead, it produces a new list with the element prepended:
> (define x '(2 3))
> (cons 1 x)
'(1 2 3)
> x
'(2 3)
Since your question is tagged functional-programming, I will assume that you probably want to know how to do this functionally, and functional programming generally discourages mutating values or bindings.
Instead of mutating a binding, you should build up a new structure functionally. The easiest way to do this is to change your use of for to for/list, which produces a list of return values:
(define C
(for/list ([i A] [j B])
(* i j)))
For this program, you could make it even simpler by using the higher-order function map, which acts like a “zip” when provided more than one list argument:
(define C (map * A B))
Since for always returns #<void>, it’s only useful for producing side-effects, and in functional programming, you generally try and keep side-effects to a minimum. For that reason, you will likely find that for/list and for/fold are actually much more commonly useful in idiomatic Racket than plain for is.
Current C list has to be given new value of (cons (* i j) C) and this can be done using set! :
(define (dProduct A B)
(define C '())
(for ([i A] [j B])
(displayln (* i j))
(set! C (cons (* i j) C))) ; NOTE set! HERE.
(for ([k C])
(displayln k)))
Note that the use of set! is strongly discouraged and for/list is much better way to achieve desired result here.
Related
I have a program that requires having a series of interchangeable functions.
In c++ I can do a simple typedef statement. Then I can call upon on a function in that list with function[variable]. How can I do this in Common Lisp?
In Common Lisp everything is a object value, functions included. (lambda (x) (* x x)) returns a function value. The value is the address where the function resides or something similar so just having it in a list, vector og hash you can fetch that value and call it. Here is an example using lists:
;; this creates a normal function in the function namespace in the current package
(defun sub (a b)
(- a b))
;; this creates a function object bound to a variable
(defparameter *hyp* (lambda (a b) (sqrt (+ (* a a) (* b b)))))
;; this creates a lookup list of functions to call
(defparameter *funs*
(list (function +) ; a standard function object can be fetched by name with function
#'sub ; same as function, just shorter syntax
*hyp*)) ; variable *hyp* evaluates to a function
;; call one of the functions (*hyp*)
(funcall (third *funs*)
3
4)
; ==> 5
;; map over all the functions in the list with `3` and `4` as arguments
(mapcar (lambda (fun)
(funcall fun 3 4))
*funs*)
; ==> (7 -1 5)
A vector of functions, where we take one and call it:
CL-USER 1 > (funcall (aref (vector (lambda (x) (+ x 42))
(lambda (x) (* x 42))
(lambda (x) (expt x 42)))
1)
24)
1008
The already given answers having provided plenty of code, I'd like to complement with a bit of theory. An important distinction among languages is whether or not they treat functions as first-class citizens. When they do, they are said to support first-class functions. Common Lisp does, C and C++ don't. Therefore, Common Lisp offers considerably greater latitude than C/C++ in the use of functions. In particular (see other answers for code), one creates arrays of functions in Common Lisp (through lambda-expressions) much in the same way as arrays of any other object. As for 'pointers' in Common Lisp, you may want to have a look here and here for a flavour of how things are done the Common Lisp way.
I'm having trouble incorporating a recursive function that squares a number.
Basically I am trying to write a function that keeps calling the Add function x number of times to square it. So if it is 7 it should call it seven times to get 49.
(define (Add a b)
(if (and (number? a) (number? b))
(+ a b)
(lambda (x)
(+ (a x) (b x)))))
(define i 0)
(define ans 0)
(define (Square a)
(when (> i a)
((Add a ans) (+ i 1 ))))
The main issue I'm running into is that the square function only goes through the loop once, I'm not sure why the condition won't update/keep going through the loop till it reaches that condition.
Writing square directly is a big pain. It's much easier to write a recursive multiply function and then just have your square function call multiply. Follow the design recipe for recursion on the natural numbers, as it appears in section 9.3 of HtDP.
By the way, if you haven't already written a bunch of recursive functions on more standard self-referential data definitions (e.g. lists), then, well, I claim that your instructor is doing in wrong.
You should make everything that changes parameters. Imagine you want to make the factorial then two values change. It's the result and the iteration of the number down to zero.
(define (factorial value)
(define (helper cur ans)
(if (zero? cur)
ans ; finished. return the answer
(helper (- cur 1) ; recur by updating n
(* cur ans)))) ; and update the answer
(helper value 1))
Again. It's exactly the same as my example in the comment except it does something else at each step. The basic building blocks are the same and something that would square the argument is very similar.
I'm confused about destructive operations in Scheme. Let's say I have a list and some destructive procedures defined in the global environment:
(define a '(a b c))
(define (mutate-obj x)
(set! x '(mutated)))
(define (mutate-car! x)
(set-car! x 'mutated))
(define (mutate-cdr! x)
(set-cdr! x 'mutated))
Then we have the following expression evaulation:
(mutate-obj! a) a => (a b c)
(mutate-car! a) a => (mutated b c)
(mutate-cdr! a) a => (mutated . mutated)
Why isn't set! having an effect on a outside its procedure when both set-car! and set-cdr! have? Why isn't the expression on the first line evaluating to (mutated)? How does all of this really work?
The first example isn't working as you imagined. Although both the x parameter and the a global variable are pointing to the same list, when you execute (set! x '(mutated)) you simply set x (a parameter local to the procedure) to point to a different list, and a remains unchanged. It'd be different if you wrote this:
(define (mutate-obj)
(set! a '(mutated)))
Now a gets mutated inside the procedure. The second and third procedures are modifying the contents of the a list, also pointed by x, so the change gets reflected "outside" once the procedure returns.
I think this is going to be a vague question because I don't know exactly what I am doing in the first place but here it goes.
I have to do a towers of hanoi problem in common lisp using lists. Basically a function takes a list of strings (names) and then moves them from peg A to peg C using peg B for storage, keeping them in the same order as they were in the list.
I have never used lisp before and I find the syntax very hard to understand.
This is my code so far
goo function is the hanoi work
(defparameter A '())
(defparameter B '())
(defparameter C '())
(defun findPeg (p1 p2) (cond ((= 0 (- 3 p1 p2))A)
((= 1 (- 3 p1 p2))B) ((= 2 (- 3 p1 p2))C)))
(defun getnum (x) (cond ((equalp x A) 0)((equalp x B)1)((equalp x C) 2)))
(defun hanoi (x) (defparameter A x) (setlength A)(goo len A C B))
(defun setlength(x) (defparameter len (list-length x)))
(defun goo (leng from to via)
(cond ((= leng 1)(push (pop A) C)) ;base case
((goo (1- leng) from via to)(push (pop A) B) ;say/do something i think
((goo (1- leng) via to from)(push (pop B) C) ;say/do something i think
))))
My problem is with the recursive calls. I am very confused as to what exactly I should be doing. I know I obviously have to move the first string in the first list to another peg, but I don't know which peg or even how to manipulate the lists. I feel like I should be using the variables that were passed into the goo function, but I cant figure out how to edit them because when I change them in the function the variables outside do not change.
Right now I am running into the error
* - SYSTEM::%EXPAND-FORM: (GOO (1- LENG) FROM VIA TO) should be a lambda expression
This is a recursive call so I don't know why it is saying that.
Basically I just want some tips or tricks on where do continue or ever where to restart because I don't even know if my approach is a good one.
Anything is greatly appreciated. Thanks
First off, using defparameter inside a DEFUN is almost never the right thing to do.
If you want to have a lexically-scoped variable, use LET (or simply name your formal parameters as you'd like them named).
Second, you have something on the form ((fun arg ..) (fun arg ...)) inside your GOO function. You want to lose the outermost parentheses.
My professor has given us a refresher assignment in clisp. One exercise is to achieve the same thing in three ways: Return a flattened list of all positive integers in a given list.
Now, there's only one way I really like doing this, using cons and recursion, but he wants me to do this using mapcan and a loop (I suspect lisp is not his first choice of language because this style of coding feels extremely resistant to the nature of lisp). I'm having a hard time working out how one would do this using a loop...I need to first start a list, I suppose?
I apologize for vague language as I'm not really sure how to TALK about using a functional language to write procedurally. Following is my first attempt.
(defun posint-loop (l)
(loop for i in l
do (if (listp i)
(posint-loop i)
(if (integerp i)
(if (> i 0)
(append i) ; this doesn't work because there's nothing to
; start appending to!
nil)
nil))))
In order to establish a new lexical binding, use let or the with keyword of loop. In order to extend an existing list, you might want to use push; if you need the original order, you can nreverse the new list finally.
Another way would be to use the when and collect keywords of loop.
Another hint: mapcan implicitly creates a new list.
Mapcan applies a function to each element of a list, expecting the function to return a list, and then concatenates those resulting lists together. To apply it to this problem, you just need to process each element of the toplevel list. If the element is a list, then you need to process it recursively. If it's not, then you either need to return an empty list (which will add no elements to the final result) or a list of just that element (which will add just that element to the final result):
(defun flatten2 (list)
(mapcan (lambda (x)
(cond
((listp x) (flatten2 x))
((and (integerp x) (plusp x)) (list x))
(t '())))
list))
(flatten2 '((a 1 -4) (3 5 c) 42 0))
;=> (1 3 5 42)
With loop, you can do just about the same thing with the recognition that (mapcan f list) is functionally equivalent to (loop for x in list nconc (funcall f x)). With that in mind, we have:
(defun flatten3 (list)
(loop for x in list
nconc (cond
((listp x) (flatten3 x))
((and (integerp x) (plusp x)) (list x))
(t '()))))