Understanding variable scope in given code - scope

I'm a beginner in Emacs lisp, so this is really a noob question. Let's say that I have to write a function that uses a loop to add 1 to each element of a numeric vector.
Here is the code I wrote (the comments indicate what I'm trying to do at each step):
(defun add-one (x)
"Use a loop to add 1 to each element of list X"
(let* ((res x) ; make a copy of X
(counter 0)) ; set counter to 0
(while (< counter (length x))
;; Replace each element of RES by adding 1:
(setcar (nthcdr counter res) (1+ (car (nthcdr counter x))))
(setq counter (1+ counter)))
;; Display result:
(message "%s" res)))
But my code seems to be destructive for x, since several calls to the function do not produce the same result:
;; Define a list:
(setq mylist '(1 2 3 4))
;; Several calls to the function:
(add-one mylist) ; -> (2 3 4 5)
(add-one mylist) ; -> (3 4 5 6)
Here is my question: I don't understand why my code is destructive (I expected the result to be (2 3 4 5) at each execution). I know that setcar is destructive, but it is applied to a copy of x, not to x itself. So why is the result changing?
Thanks!

For the sake of clarity:
Despite the fact you do not copy input list, your code is not at all lispy. Try this instead:
(mapcar '1+ '(1 2 3 4))

Let does not make a copy of anything, so this assigns the value referenced by the variable x to the variable res. Hence any changes to the list referenced by res also change the list referenced by x
(let* ((res x) ; make a copy of X

Related

List comprehension not ending in a square bracket, console freezing

Entering a list comprehension into GHCi does not generate a list, the final square brackets are missing, and the console freezes. This is what I have come up with:
[13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000]
I believe the problem lies either with x <- [1..], or 13*x + 3 <= 1000. By 13*x + 3 <= 1000 I meant to determine the upper limit of the values x in x <- [1..] can take.
I'm given back a result [341, but it does the second square bracket is missing, and the console freezes.
Your program enters an infinite loop.
The first number is 341, but in order to produce the next number, your program keeps looking through all the subsequent values of x, evaluates all the guards for those values, and checks if all the guards are true. The very last guard, 13*x + 3 <= 1000 never becomes true again, so the program just keeps enumerating values of x forever. It's looking for the next such x for which all guards are true, and as soon as it finds one, it's going to print it. But such x never comes.
If you want the list to end once x*13 + 3 > 1000, you have to use takeWhile:
... | x <- takeWhile (\y -> y*13 + 3 <= 1000) [1..], ...
That way the list will actually stop when it reaches 1000. No more values of x would be produced.
You're giving the compiler way too much credit. It isn't going to carefully analyse your list comprehension in order to deduce that past a certain point there will be no more results, and it should call the list complete. It only does what you tell it to do.
In this case what you told it to do is:
[ 13*x + 3 -- produce numbers of the form 13*x + 3
| x <- [1..] -- by searching all x from [1..]
, rem (13*x + 3) 12 == 5 -- allowing only x that meet this condition
, mod (13*x + 3) 11 == 0 -- and this condition
, 13*x + 3 <= 1000 -- and this condition
]
So it prints [341 and "freezes" because it's still trying to compute the rest of that list. You don't see anything happening, but internally it's drawing ever bigger x from [1..] and diligently checking those conditions to realise that the number shouldn't be included. But it never hits the end of [1..] in order to stop, so it never gets up to printing the ] and waiting for more input.
With your code you are explicitly telling the compiler that you want to search every number in the infinite1 list [1..]. You are then expecting it to notice that 13*x + 3 <= 1000 can only be true for x drawn from a finite prefix of [1..] and thus actually not search the entire list [1..] as you instructed2.
That is a perfectly reasonable thing to want, and I can imagine a system capable of pulling that off (at least with simple conditions like this). So testing it out like this to see if it works is a good idea! However unless someone actually told you that figuring out enumeration upper bounds from conditions in list comprehensions is a feature that GHC can provide, it shouldn't be surprising that it never completes when you tell it to search an infinite list.
For this style of list comprehension (getting all numbers in a range meeting certain conditions) you normally shouldn't use [1..] and then try to impose a stopping condition. Just figure out that the last number that will pass 13*x + 3 <= 1000 and use [1..76] as your generator instead. You can even have Haskell figure it out for you with [1 .. (1000 - 3) div 13].
You use a generator like [1..] when you want to get all numbers of the right form. Then you can use functions like take or takeWhile to get a finite section at the point where you want to use it for something. e.g.
Prelude> let xs = [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0]
Prelude> takeWhile (<= 1000) xs
[341]
Prelude> take 5 xs
[341,2057,3773,5489,7205]
In fact the simplest and most direct way to express what you want in a single expression is this:
takeWhile (<= 1000) [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0]
Everything in a list comprehension (except the generator expression) is only talking about a single element at a time. There's just no way to express concepts that are talking about the returned list as a whole, like "stop searching once the returned numbers go out of this range". But that concept is trivial to express outside of list comprehension as a normal function (takeWhile (<= 1000)). Don't feel like you have to shoehorn your entire computation into a single list comprehension.
1 Strictly speaking it's infinite if you're using a type like Integer (which is the type Haskell will pick without any other code using the result to impose other constraints on the type). If you're using Int then it's technically finite, and your list comprehension will eventually end when it "runs out of numbers". [1..] as a list of Int is still impractically vast for an exhaustive search, however.
But if you use a smaller type, like Word16 (needs to be imported from Data.Word) then you can in fact finish your original list comprehension in a practical amount of time. (Though I had to tweak it a little to make sure the 13*x stuff was computed in a larger type so it doesn't overflow)
Prelude> import Data.Word
Prelude Data.Word> [13*x + 3 | x <- [1 :: Word16 ..], let x' = fromIntegral x, rem (13*x' + 3) 12 == 5, mod (13*x' + 3) 11 == 0, 13*x' + 3 <= 1000]
[341]
2 While I'm being pedantic in the footnotes, if your original list comprehension is being evaluated as a list of Int it wouldn't even be valid to just stop after x grows high enough that 13*x + 3 <= 1000 fails for the first time. Try this:
Prelude Data.Word> let x = 768614336404564650 :: Int
Prelude Data.Word> 13*x + 3 <= 1000
True
This happens because Int does in fact have an upper bound, so a large enough Int will overflow back to negative when you multiply it by 13. So when searching [1..] as [Int] the compiler is in fact right to keep looking past x = 77; there are almost certainly more numbers in your original list comprehension if it's [Int], they just take a long time to reach.
Again a good way to demonstrate is to use a smaller finite type, like Word16. If I use your original list comprehension as [Word16] without modifying it to avoid overflow in the conditions, you get this:
Prelude Data.Word> [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000] :: [Word16]
[341,605,209,869,473,77,737]
Even if the compiler was smart enough to know the regions of [1..] that could possibly pass 13*x + 3 <= 1000 condition, it's never going to be able to read your mind and know whether the overflow-produced numbers are solutions you intended or are the result of a bug in your code. It just does what you tell it to do.

Intersection-sets using iterator in Scheme

I am trying to create a function that takes two set objects and returns a new set object that is the intersection of those two objects while using an iterator.
Here are some functions that I used, basic-set1 and basic-set2 are set objects that are initially empty.
((basic-set1 'get-set))
>(d c b a)
((basic-set2 'get-set))
>(a b)
(define my-iterator3 basic-set1)
((my-iterator3 'next))
> d
((my-iterator3 'next))
> c
((my-iterator3 'hasnext))
> #t
My desired output
(intersection-sets basic-set1 basic-set2)
> (b a)
This is the code I have so far.
(define (intersect-sets set1 set2)
(define my-iterator3 ((set1 'get-iterator )))
(define result (basic-set))
(define (iter)
(let ((x ((my-iterator3 'next))))
(cond ((not ((my-iterator3 'hasnext))) result)
(((set2 'element?) x)
(begin ((result 'insert) x)
(iter)))
(else
(iter)))))
(iter))
Tested output:
(intersect-sets basic-set1 basic-set2)
>#<procedure:...Problem3.rkt:60:2
I'm kind of stumped. Any help would be appreciated.
As far as I can tell your code is correct. The first cond clause returns result, which is a procedure. If you want the set returned as a list try ((not ((my-iterator3 'hasnext))) ((result 'get-set))) as your first cond clause in iter

What is the core difference between strings and numbers in Common Lisp?

Being new with CL, I play a lot with simple algorithms. For instance, I tried to implement a function for removing all unique elements in a list.
(1 2 2 3 3 4 5 3) -> (2 2 3 3 3)
First attempt lead to this code:
(defun remove-unique (items)
(let ((duplicates (set-difference items (remove-duplicates items :test #'equal))))
(append duplicates (remove-duplicates duplicates :test #'equal))))
This works ok with strings but does always return NIL for numbers. Reading a bit more about set-difference I've learned that it isn't suppose to work with duplicate populated lists at all, it just works somehow in my case, so I abandoned the approach as unportable and moved along.
Another attempt is:
(defun remove-unique (items)
(loop for item in items
when (member item (cdr (member item items)))
collect item))
And this works ok with numbers, but returns NIL for strings.
Apparently there is a core difference between strings and numbers I don't understand. How come list processing functions such as member and set-difference work differently on them?
The equality comparison for numbers, characters and strings is indeed different. Equal, which you should be wary to use because it is more expensive, does structure equality (so it descends on some objects). eq does object equality. And eql does object equality for most cases except for numbers (where they check type and value) and characters (where they check 'value')
See the hyperspec entries for equal, eql and eq for more information.
Strings are more related to lists than numbers since both lists and strings are sequences.
"Hello" is a sequence (compund data type) starting with the primitive character value #\H and ending with #\o.
'(1 2 3) is a sequence (compond data type) starting with the primitive numeric value 1 and ending with 3.
Characters are similar to numbers in that they are primitive values. Primitive values can be compared using eql while sequences, that are not the same object, can be compared using equal
(setq list1 (list 1 2 3))
(setq list2 (list 1 2 3))
(eql list1 list2)
;==> NIL
(equal list1 list2)
;==> T
;; comparing first element of both lists using eql
(eql (car list1) (car list2))
;==> T
(setq string1 "Hello")
(setq string2 "Hello")
(eql string1 string2)
;==> NIL
(equal string1 string2)
;==> T
;; comparing first character of both strings using eql
(eql (elt string1 0) (elt string2 0))
;==> T
Most (if not all) functions in Common Lisp that compares something usually has an optional named argument :test where you can supply how elements compare. the default usually is eql. To make them behave corretly with sequences you need to supply #'equal as :test.
(defun remove-unique (items &key (test 'eql))
(loop
:with table := (make-hash-table :test test)
:for element :in items :do
(setf (gethash element table)
(1+ (gethash element table 0)))
:finally
(return
(loop
:for k :being :the :hash-keys :of table
:using (:hash-value v)
:when (> v 1) :nconc (make-list v :initial-element k)))))
(defun remove-unique (items &key (test 'eql))
(loop
:with table := (make-hash-table :test test)
:for element :in items :do
(setf (gethash element table)
(1+ (gethash element table 0)))
:finally
(return
(loop
:for element :in items
:unless (= 1 (gethash element table))
:collect element))))
I'd probably use the first variant because it makes less reads from hash-table, but you'd need to check that items in the list aren't modified later in place.
(remove-unique '("1" "2" "2" "3" "3" "4" "5" "3") :test #'equal)
gives:
("2" "2" "3" "3" "3")
but
(remove-unique '("1" "2" "2" "3" "3" "4" "5" "3"))
gives:
NIL

get all fields of object

Is it possible in racket to get all fields of an object at the same time?
I would like basically to convert an object to a hash table with field names as keys and field values as values.
I found a function (field-names obj), but then I don't know how to use the returned field names to get the values from the obj. The function get-field can be used to get the value of a field, but I dont know how to use it with a value:
> (define x% (class object% (init-field x y) (super-new)))
> (define obj (make-object x% 1 2))
> (get-field x obj)
1
> (field-names obj)
'(y x)
> (define field-name (second (field-names obj)))
> field-name
'x
> (get-field field-name obj)
get-field: given object does not have the requested field
field name: field-name
object: (object:x% ...)
errortrace...:
context...:
/usr/lib/racket/collects/racket/private/class-internal.rkt:4906:0: obj-error29
/usr/lib/racket/collects/racket/private/misc.rkt:87:7
Here's some code to get you started
#lang racket
> (define x% (class object% (inspect #f) (init-field x y) (super-new)))
> (define obj (make-object x% 1 2))
> (let-values (((name field-cnt field-name-list field-accessor field-mutator super-class skipped)
(class-info x%)))
(for/hash ((name field-name-list)
(idx field-cnt))
(values name (field-accessor obj idx))))
'#hash((x . -1) (y . 0))
You may want to change the inspector from #f to something less vulnerable, but open enough for your needs. Read up on class-info and inspectors in general.

Writing Matrix conversions with Scheme for GIMP

I want to write some nice Math with DrRacket(R5RS but not only) (Racket Tag is a bit empty).
I would really like to code some matrix stuff like:
(3 3 3) (5 3 4)
(4 4 4) -> (5 3 4)
(5 5 5) (5 3 4)
And other stuff like this to set up some nice gimp filters...
Some folks pointed out, this could be done via lists inside lists, but I can't think of a practical example here...
I am looking forward to your reply.
Yours sincerely, Andreas_P
A few notes:
1) what do you mean with Scheme "is built in within the core"? GIMP now has a native Python-fu along with Script-fu
2) the Lisp that won Google AI Challenge is Common Lisp, not Scheme
3) I am not sure, but the Script-fu console states TinyScheme, thus I would expect it to be really essential, with little library support, with respect to more complete Scheme implementations
Anyway, I tried a few example on matrices "the Scheme way". For the sake of simplicity, they lack any control on the input data, but for simple examples they work fine on DrRacket.
(define (vect-sum x y)
(cond
((empty? x) empty)
(else
(cons (+ (first x) (first y)) (vect-sum (rest x) (rest y))))))
(define (scalar-prod a v)
(cond
((empty? v) empty)
(else
(cons (* a (first v)) (scalar-prod a (rest v))))))
(define (matr-sum x y)
(cond
((empty? x) empty)
(else
(cons (vect-sum (first x) (first y))
(matr-sum (rest x) (rest y))))))
(define (matr-scalar-prod a m)
(cond
((empty? m) empty)
(else
(cons (scalar-prod a (first m)) (matr-scalar-prod a (rest m))))))
And now a simple test on the data as in the other answer:
> (define m '((3 3 3)(5 3 4)(4 4 4)))
> m
'((3 3 3) (5 3 4) (4 4 4))
> (matr-scalar-prod 3 m)
'((9 9 9) (15 9 12) (12 12 12))
HHi, I'd highly recommend you to use Python instead of Scheme for writing GIMP scripts, unless you want to learn Scheme for recreational purposes.
One of the tenets in Python is to not allow the language to stay between you and your problem, and writing your own Matrix manipulation code is trivial. If you want high performance ops, you can use a third party library such as NumPy (even from inside GIMP environment) to get it.
So, for a Matrix class that would allow scallar multiplication and adding one could simply write:
class Matrix(object):
def __init__(self, rows, cols, *args):
self.rows = rows
self.cols = cols
self.values = args
def __getitem__(self, (i,j)):
return self.values[i * self.cols + j]
def __setitem__(self,(i,j), value):
self.values[i * self.cols + j] = value
def __add__(self, other):
values = []
for i in range(self.rows):
for j in range(self.cols):
values.append(self[i,j] + other[i,j])
return Matrix(self.rows, self.cols, *values)
def __mul__(self, N):
return Matrix(self.rows, self.cols,*(N * v for v in self.values))
def __repr__(self):
return "\n".join (" ".join(str(self[i,j]) for j in range(self.cols)) for i in range(self.rows) )
Example on Python's interactive console:
>>> m = Matrix(3,3,
... 3,3,3,
... 5,3,4,
... 4,4,4)
>>> m * 3
9 9 9
15 9 12
12 12 12
Implementing more operations is equally simple, and, for calling GIMP's API functions, with this example class, you can just use m.values, that is simply a list with all the matrix values in sequence - which is the way GIMP PDB's functions use them. (Such as pdb.gimp_drawable_transform_matrix or pdb.plug_in_convmatrix. (I suppose you've found GIMP's API browser under the help menu - the same functions are available in Scheme and in Python, just replace the "-" in the names for "_")

Resources