This code discussing named arguments in Clojure from "The Joy of Clojure":
(defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}]
(float (/ (- (p2 1) (p1 1))
(- (p2 0) (p1 0)))))
(slope :p1 [4 15] :p2 [3 21])
The function itself, I understand it -no problem with destructuring- but I don't understand the calling.
Are we passing four arguments to slope? how vectors are getting assigned to :p1 and :p2?
You are passing four arguments to slope, yes. The [] part of slope specifies the parameters, in which & means "slurp all additional parameters into this form", which then specifies that it is looking for arguments that form a map with keys p1 and p2 (and gives default values if either doesn't exist).
Related
I'm working on some numerical computations in Common Lisp and I need to compute a linear combination of several vectors with given numerical coefficients. I'm rewriting a piece of Fortran code, where this can be accomplished by res = a1*vec1 + a2*vec2 + ... + an*vecn. My initial take in CL was to simply write each time something like:
(map 'vector
(lambda (x1 x2 ... xn)
(+ (* x1 a1) (* x2 a2) ... (* xn an)))
vec1 vec2 ... vecn)
But I soon noticed that this pattern would recur over and over again, and so started writing some code to abstract it away. Because the number of vectors and hence the number of lambda's arguments would vary from place to place, I figured a macro would be required. I came up with the following:
(defmacro vec-lin-com (coefficients vectors &key (type 'vector))
(let ((args (loop for v in vectors collect (gensym))))
`(map ',type
(lambda ,args
(+ ,#(mapcar #'(lambda (c a) (list '* c a)) coefficients args)))
,#vectors)))
Macroexpanding the expression:
(vec-lin-com (10 100 1000) (#(1 2 3) #(4 5 6) #(7 8 9)))
yields the seemingly correct expansion:
(MAP 'VECTOR
(LAMBDA (#:G720 #:G721 #:G722)
(+ (* 10 #:G720) (* 100 #:G721) (* 1000 #:G722)))
#(1 2 3) #(4 5 6) #(7 8 9))
So far, so good...
Now, when I try to use it inside a function like this:
(defun vector-linear-combination (coefficients vectors &key (type 'vector))
(vec-lin-com coefficients vectors :type type))
I get a compilation error stating essentially that The value VECTORS is not of type LIST. I'm not sure how to approach this. I feel I'm missing something obvious. Any help will be greatly appreciated.
You've gone into the literal trap. Macros are syntax rewriting so when you pass 3 literal vectors in a syntax list you can iterate on them at compile time, but replacing it with a bindnig to a list is not the same. The macro only gets to see the code and it doesn't know what vectors will eventually be bound to at runtime when it does its thing. You should perhaps make it a function instead:
(defun vec-lin-com (coefficients vectors &key (type 'vector))
(apply #'map
type
(lambda (&rest values)
(loop :for coefficient :in coefficients
:for value :in values
:sum (* coefficient value)))
vectors))
Now you initial test won't work since you passed syntax and not lists. you need to quote literals:
(vec-lin-com '(10 100 1000) '(#(1 2 3) #(4 5 6) #(7 8 9)))
; ==> #(7410 8520 9630)
(defparameter *coefficients* '(10 100 1000))
(defparameter *test* '(#(1 2 3) #(4 5 6) #(7 8 9)))
(vec-lin-com *coefficients* *test*)
; ==> #(7410 8520 9630)
Now you could make this a macro, but most of the job would have been done by the expansion and not the macro so basically you macro would expand to similar code to what my function is doing.
Remember that macros are expanded at compile-time, so the expression ,#(mapcar #'(lambda (c a) (list '* c a)) coefficients args) has to be meaningful at compile-time. In this case, all that mapcar gets for coefficients and args are the symbols coefficients and vectors from the source code.
If you want to be able to call vec-lin-com with an unknown set of arguments (unknown at compile-time, that is), you'll want to define it as a function. It sounds like the main problem you're having is getting the arguments to + correctly ordered. There's a trick using apply and map to transpose a matrix that may help.
(defun vec-lin-com (coefficients vectors)
(labels
((scale-vector (scalar vector)
(map 'vector #'(lambda (elt) (* scalar elt)) vector))
(add-vectors (vectors)
(apply #'map 'vector #'+ vectors)))
(let ((scaled-vectors (mapcar #'scale-vector coefficients vectors)))
(add-vectors scaled-vectors))))
This isn't the most efficient code in the world; it does a lot of unnecessary consing. But it is effective, and if you find this to be a bottleneck you can write more efficient versions, including some that can take advantage of compile-time constants.
I'm looking for a way how to use map function in more custom way. If there is a different function for what I'm trying to achieve, could you please let me know this.
;lets say i have addOneToEach function working as bellow
(defn plusOne[singleInt]
(+ 1 singleInt))
(defn addOneToEach[intCollection] ;[1 2 3 4]
(map plusOne intCollection)) ;=>(2 3 4 5)
;But in a case I would want to customly define how much to add
(defn plusX[singleInt x]
(+ x singleInt))
(defn addXToEach[intCollection x] ;[1 2 3 4]
;how do I use plusX here inside map function?
(map (plusX ?x?) intCollection)) ;=>((+ 1 x) (+ 2 x) (+ 3 x) (+ 4 x))
I'm not looking for a function that adds x to each in the collection, but a way to pass extra arguments to the function that map is using.
another option to the already mentioned would be partial (note that in the example the order of the params does not matter, since you just add them, but partial binds them from left to right, so beware):
user=> (doc partial)
-------------------------
clojure.core/partial
([f] [f arg1] [f arg1 arg2] [f arg1 arg2 arg3] [f arg1 arg2 arg3 & more])
Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args.
nil
user=> (defn plus-x [x i] (+ x i))
#'user/plus-x
user=> (map (partial plus-x 5) [1 2 3])
(6 7 8)
There are several ways to go about it. One is using an explicit local function via letfn:
(defn add-x-to-each [ints x]
(letfn [(plus-x [i]
(+ i x))]
(map plus-x ints)))
For this small piece of code this is probably overkill and you can simply streamline it via an anonymous function:
(defn add-x-to-each [ints x]
(map #(+ % x) ints))
Both of these solutions basically apply the use of a closure which is an important concept to know: it boils down to defining a function dynamically which refers to a variable in the environment at the time the function was defined. Here we defer the creation of plus-x (or the anonymous) function until x is bound, so plus-x can refer to whatever value is passed in to add-x-to-each.
You almost got it right.
There are several possible ways:
1.
(defn addXToEach[intCollection x]
(map #(plusX % x) intCollection))
#(%) means same as (fn [x] (x)) (be aware that x is being evaluated here).
2.
(defn addXToEach[intCollection x]
(map (fn [item] (plusX item x)) intCollection))
3.
(defn addXToEach[intCollection x]
(map #(+ % x) intCollection))
and then you don't have to define your plusX function.
Hope it helps!
You are applying map to one collection, so the function that map applies must take one argument. The question is, how is this function to be composed?
The function
(defn plusOne [singleInt]
(+ 1 singleInt))
... works. It is otherwise known as inc.
But the function
(defn plusX [singleInt x]
(+ x singleInt))
... doesn't work, because it takes two arguments. Given a number x, you want to return a function that adds x to its argument:
(defn plusX [x]
(fn [singleInt] (+ x singleInt))
You can use a function returned by plusX in the map.
It is when you compose such a function that you can use extra arguments. This kind of function, composed as an expression involving captured data, is called a closure.
For example, (plusX 3) is a function that adds 3 to its argument.
(map (plusX 3) stuff)
;(4 5 6 7)
As you see, you don't need to name your closure.
Specifically for + the following will also work:
(map + (repeat 4) [3 4 9 0 2 8 1]) ;=> (7 8 13 4 6 12 5)
Of course, instead '4' put your number, or wrap with (let [x 4] ...) as suggested above.
It might not be the most performant, although, I guess.
I am struggling with understanding what I really need to do, and would like some outside input or a point to a good reference. I have been asked to use procedural representation to "implement sets of numbers." Each set will be a one argument function that takes a number and decides if the number is in the set. A few functions (that I have read can be defined in one line) that I have to create:
A function that returns a function taking a number as an argument and checks if the number is in the set.
A union function that returns the set of all elements in arg1 or arg2
Intersection function of above
Function that returns elements in arg1 but not arg2
etc.
Now I know this is simply enclosing a lambda function, but I guess I am confused on how to represent a set and check it within the lambda function? If someone could point me in the right direction I would appreciate it.
You have to realise that the first function in your TODO list is the constructor. The rest falls out from there I think.
(define (make-set x) (lambda (y) (eq? x y)))
(define (union x y) (lambda (z) (or (x z) (y z))))
(define (intersection x y) (lambda (z) (and (x z) (y z))))
(define (difference x y) (lambda (z) (and (x z) (not (y z)))))
(define set-5 (make-set 5))
(set-5 4)
(set-5 5)
(define set-45 (union (make-set 4) (make-set 5)))
(set-45 3)
(set-45 5)
(define set-34 (union (make-set 3) (make-set 4)))
(define set-4 (intersection set-34 set-45))
(set-4 3)
(set-4 5)
(set-4 4)
(define set-3 (difference set-34 set-45))
(set-3 4)
(set-3 5)
(set-3 3)
A function is defined in ACL2, and we are tasked with creating a measure function to help prove termination. This is the function definition:
(defunc f (x a)
:input-contract (and (integerp x) (listp a))
:output-contract (integerp (f x a))
(cond
((endp a) 68)
((equal (len a) x) 71)
((equal (len a) (+ x 1)) 74)
((< x (len a)) (f (+ x 1) (rest a)))
(t (f (- x 1) (cons 1 a)))))
And a solution measure function is this (in shorthand):
(m x a) = (if (equal (len a) (+ x 1))
0
(abs (- (len a) x)))
We were able to determine the else case of the measure function would be included, based on the two recursive calls in the function. However, we don't understand the rest of it, and the process that went into figuring out this measure function.
For reference, a measure function:
m is an admissible function deļ¬ned over the parameters of f;
m has the same input contract as f;
m has an output contract stating that it always returns a natural number; and
on every recursive call, m applied to the arguments to that recursive call decreases,
under the conditions that led to the recursive call.
What is the process that led to determining this measure function?
When determining a measure function, the question to ask yourself is: What is the "potential energy" that gets used up on each iteration, to the point where at some point it's all gone and the iteration stops?
The first place to look is usually the termination conditions. In this case there are three, but the last two are the most interesting: they say we stop iterating if the difference between x and (len a) is too small.
That gives us an idea: what if the potential energy is difference between (len a) and x? To see whether that makes sense, we need to check the recursive cases and make sure that each one of them uses up some energy, i.e. decreases the difference. Things look pretty good here:
If x is less than (len a) we increase x by 1 and decrease (len a) by 1. So if the difference between them was n, then on the next iteration it will be n-2 unless x = (len a) - 1.
Otherwise x is greater than (len a) and we decrease x by 1 and increase (len a) by 1. Again, if the difference between them was n, then on the next iteration it will be n-2 unless x = (len a) + 1.
From there it's pretty easy to see that we should choose x = (len a) + 1 as our "low energy state", since it handles the pesky detail of those two unless clauses.
I am brand new to Scheme and am working on an assignment to implement stochastic gradient descent. So far I believe I have the structure of the program correct however my procedure that takes the derivative of a function f(x) is giving me some trouble. In my "try" loop at the bottom of the code I recursively call (try (func-eval guess)) where (func-eval guess) calculates the next guess of my function's local minimal with the formula *x - alpha*f'(x)* where alpha = 0.1.
I seem to be getting an error when calculating the derivative... I am using Dr.Racket IDE and it has highlighted this following line as being problematic:
(f (+ x dx)) ... which is the second line in my local derivative procedure:
(define (local-minimal first-guess)
;A way to check a guess
(define(good-enough? val1 val2)
(<(abs(- val1 val2)) 0.00001))
; x_new = x_old - alpha*f'(x) /// f(x)=(x+1)^2+2 //// alpha = 0.1
(define (func-eval x)
(- x (* 0.1((derivative (+ 2(expt (+ x 1) 2)) 0.00001)x))))
(define (derivative f dx)
(lambda (x)
(/ (- (f (+ x dx)) (f x))
dx)))
; trys the guess
(define (try guess)
(if (good-enough? guess -1)
guess
(try (func-eval guess))))
(try first-guess))
I am getting an error saying:
application: not a procedure;
expected a procedure that can be applied to arguments
given: 3
arguments...:
-1.99999
Is this a syntax error? I thought that I would be able to say f(x+dx) by using (f (+ x dx)) .... does this mean that I need to put an operator before the f in those parenthesis?
The highlighting and error message are together telling you something useful: the thing derivative is receiving as its first argument f isn't a function, which it needs to be to called in (f (+ x dx)). Where does the argument come from? We could run DrRacket's debugger, but here we can just look at the code -- the only place derivative is called from is the first line of func-eval, so that's where we must have passed a number instead of a function. Sure enough, (+ 2 (expt (+ x 1) 2)) (with x bound) is just a number, and trying to apply this gives an error.
When calling derivative, the first argument has to be a function. In the following procedure call, the expression in the first argument gets evaluated to a number, not a function:
(derivative (+ 2 (expt (+ x 1) 2)) 0.00001)
To fix it, pack the expression inside a lambda, which makes it an actual function:
(derivative (lambda (x) (+ 2 (expt (+ x 1) 2))) 0.00001)