I must be missing something very basic here.
I need to extract a capture group from a match in common lisp.
When I eval in the interpreter (an sbcl implementation):
`(cl-ppcre::scan-to-strings ".*?(\\d).png" "sample1.png")`
I get:
"sample1.png"
#("1")
But if I bind that expression to a value, say
`(setq number (cl-ppcre::scan-to-strings ".*(\\d).png" "sample1.png"))`
The value of number is becomes "sample1.png". How do I get the "1", which is printed?
Your question
You are looking for
(setf (values match position)
(cl-ppcre::scan-to-strings ".*(\\d).png" "sample1.png"))
See also multiple-value-bind et al.
Under the hood
Common lisp functions can return multiple values.
This corresponds to "tuple" return value in other languages, such as Python.
So, when a lisp function, such as floor, return multiple values, a Python user will write something like
(f,r) = floor(10,3)
and floor will (usually) allocate a tuple, which is captured when you write fr = floor(10,3).
CL multiple values do not allocate extra storage, but the extra values are discarded unless you specifically ask for them:
(setf (values f r) (floor 10 3))
will capture both values, but (setf f (floor 10 3)) will discard r.
Related
as a lisp newbie i'm stuck with a general problem: I want to query data, generate a sum over it and want to calculate further with this results.
For example i sum up 33 77 and want to divide the result:
(defun sum (L)
(reduce '+ L))
(/ 999 (sum '(33 77)))
Without the divison i receive the correct sum. When i'm trying to proceed further, i get an error that a numerical function was given an argument.
A type-of query (type-of '(sum '(33 77))) says it's CONS
What's the correct handling for results for further calculation?
(type-of '(sum '(33 77)))
The evaluation of the above consists first in evaluating '(sum '(33 77)), and call function type-of with the result of the evaluation.
'(sum '(33 77)) is the same as (quote (sum (quote (33 77)))), except that the apostrophe is a reader syntax ' that turns what follows, say x, into (quote x).
The quote form is self-evaluating, meaning the value it evaluates to is the exact value that was quoted, here (sum '(33 77)).
That value is data representing code: it literally is a list, built at read-time, that contains the symbol sum followed by another element, a list whose first element is quote that is followed by another list containing 33 and 77, literal numbers.
Since the value of your expression is a list, and since lists are built by chaining cons-cells, it is normal that type-of returns cons.
If you remove one level of quotes:
(type-of (sum '(33 77)))
Then the evaluation of (sum '(33 77)) follows the normal evaluation of function calls, by first evaluating the argument, '(33 77), a literal list, and calling sum with it. Your function returns the sum, 110, and this is the value that is given when calling type-of. In that case, you should obtain a numerical type.
I need to write a recursive method in lisp that doubles the odd values and leaves the even values alone.
So far i have:
(defun MY-DOUBLE-ODD (n)
(if (oddp n)
(setq n (* n 2)))
n)
However, I just can't figure out how to have this recursive method go through an entire list.
How do I fix it to make it iterate through (MY-DOUBLE-ODD (1 2 3 4 5 6))
??
Your solution should not involve setq at all. The recursion should be used to iterate the list of arguments, using car to get the first element, cdr to get the rest of the list to recurse on, and cons to construct the result on return from the recursive call.
I am trying to implement tail call recursive factorial in Common Lisp, to try it and just experience it.
I copied some code and rewrote it in Common Lisp like so:
(defun tailrecsum (x &key (running-total 0 running-total-p))
(if (= x 0)
(if running-total-p running-total 0)
(tailrecsum (- x 1) (+ running-total x))))
However, I get first a warning:
SIMPLE-WARNING:
The function has an odd number of arguments in the keyword portion.
And when trying to run it, I get an error:
SIMPLE-PROGRAM-ERROR:
odd number of &KEY arguments
Why can't I have an odd number of keyword arguments? What's the problem with that and what can I do about it?
For example in Python I could write:
def func(a, b=10):
print([a, b])
So I would have an odd number, one, of keyword arguments. No issues there.
The error doesn't refer to the number of keyword parameters; rather it means the number of arguments you call the function with. Since keywords arguments by definition need to be in pairs (:KEYWORD VALUE), having odd number of arguments means you must be missing something.
In this case you're missing the keyword in
(tailrecsum (- x 1) (+ running-total x))
which should be
(tailrecsum (- x 1) :running-total (+ running-total x))
I am learning OCaml. I know that OCaml provides us with both imperative style of programming and functional programming.
I came across this code as part of my course to compute the n'th Fibonacci number in OCaml
let memoise f =
let table = ref []
in
let rec find tab n =
match tab with
| [] ->
let v = (f n)
in
table := (n, v) :: !table;
v
| (n', v) :: t ->
if n' = n then v else (find t n)
in
fun n -> find !table n
let fibonacci2 = memoise fibonacci1
Where the function fibonacci1 is implemented in the standard way as follows:
let rec fibonacci1 n =
match n with
| 0 | 1 -> 1
| _ -> (fibonacci1 (n - 1)) + (fibonacci1 (n - 2))
Now my question is that how are we achieving memoisation in fibonacci2. table has been defined inside the function fibonacci2 and thus, my logic dictates that after the function finishes computation, the list table should get lost and after each call the table will get built again and again.
I ran some a simple test where I called the function fibonacci 35 twice in the OCaml REPL and the second function call returned the answer significantly faster than the first call to the function (contrary to my expectations).
I though that this might be possible if declaring a variable using ref gives it a global scope by default.
So I tried this
let f y = let x = ref 5 in y;;
print_int !x;;
But this gave me an error saying that the value of x is unbounded.
Why does this behave this way?
The function memoise returns a value, call it f. (f happens to be a function). Part of that value is the table. Every time you call memoise you're going to get a different value (with a different table).
In the example, the returned value f is given the name fibonacci2. So, the thing named fibonacci2 has a table inside it that can be used by the function f.
There is no global scope by default, that would be a huge mess. At any rate, this is a question of lifetime not of scope. Lifetimes in OCaml last as long as an object can be reached somehow. In the case of the table, it can be reached through the returned function, and hence it lasts as long as the function does.
In your second example you are testing the scope (not the lifetime) of x, and indeed the scope of x is restricted to the subexpresssion of its let. (I.e., it is meaningful only in the expression y, where it's not used.) In the original code, all the uses of table are within its let, hence there's no problem.
Although references are a little tricky, the underlying semantics of OCaml come from lambda calculus, and are extremely clean. That's why it's such a delight to code in OCaml (IMHO).
Can anyone give me a well-written implementation of how to order a list of pairs in scheme using a helper function (based on the value of the car of each of the pairs)? For example, '((3 2) (1 2) (8 4) (0 6)) should be ordered as '((0 6) (1 2) (3 2) (8 4)). This seems like such a simple thing to do, but for some reason I am drawing a blank.
Well, first of all you can use your favorite built-in sort routine, and specify it be sorting by car, e.g. in Common LISP
(sort ls #'< :key #'car)
if your Scheme lacks the ability to specify key, you can emulate this by a comparison procedure
(sort ls (lambda (a b) (< (car a) (car b))))
second, if you want to reimplement this, you could use the approach of mergesort: break up your list into monotone increasing portions, then merge them pairwise until there's only one left. In Haskell,
mergesortBy f xs
| null xs = []
| [s] <- until (null.tail) (pairwise (mergeBy f)) (breakup xs) = s
pairwise g (a:b:t) = g a b : pairwise g t
pairwise _ t = t
breakup xs = [[x] | x <- xs] -- a list of (a list of x) for x in xs
since the portions are monotone increasing (or at least non-decreasing), mergeBy can be easily implemented.
Of course, a "well-written" implementation will replace the rudimentary breakup shown here with an initial phase which will try to make longer chunks, preserving the non-decreasing and reversing the non-increasing chunks on the go (a Haskell example is here). pairwise and mergeBy (and perhaps even breakup) functions will have to be fused into one, to make the overall implementation more on-line, since Scheme is (usually) a strict (i.e. non-lazy) language. You could use explicit suspensions in the internal lists being merged, so that taking a few first elements off a sorted list is an O(n) operation.