Writing Matrix conversions with Scheme for GIMP - linux

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 "_")

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.

Converting Iterative Code to Recursive Code Python3

I'm a beginner programming student and I've been studying recursion functions in Python3 lately. I'm working on a code that basically provides minimum steps requires for a number N to be M undergoing processes of adding 1, divide 2, or multiple 10. I did an iterative function that works well, but as a beginner student of recursive functions I want to be able to convert the code to a recursive code and in this code I was not successful.
I've been reading about this process lately, but as I said it was a very hard implementation for my skills. I know if I want to convert an iterative code I need to use the main loop condition as my base case and the body of the loop as the recursive step and that is all I know.
I would really appreciate it if you could help me to find the base case and the recursive steps of this code. I don't want you to write my code, I want you to help me in reaching my goals.
ITERATIVE CODE
def scape(N, M, steps=0):
if N == M:
return 0
currentoptions = [N]
while True:
if M in currentoptions:
break
thisround = currentoptions[:]
currentoptions = []
for i in thisround:
if (i%2) == 0:
currentoptions.append(i // 2)
currentoptions.append(i + 1)
currentoptions.append(i * 10)
steps += 1
return steps
EXAMPLE
print(scape(8,1))
OUTPUT -> 3
Because 8/2 -> 4/2 -> 2/2 = 1
It is difficult to use pure recursion here (without passing around auxiliary data structures). YOu could do sth along the following lines:
def scape(opts, M, steps=0):
if M in opts:
return steps
opts_ = []
for N in opts:
if not N%2:
opts_.append(N // 2)
opts_.extend((N + 1, N * 10))
return scape(opts_, M, steps+1)
>>> scape([8], 1)
3
Or in order to keep the signature (and not pass around redundant arguments), you could use a recursive helper function:
def scape(N, M):
steps = 0
def helper(opts):
nonlocal steps
if M in opts:
return steps
opts_ = []
for N in opts:
if not N%2:
opts_.append(N // 2)
opts_.extend((N + 1, N * 10))
steps += 1
return helper(opts_)
return helper([N])
>>> scape(8, 1)
3

Understanding variable scope in given code

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

How to store one part of a return in a variable

Alright. So, I have a function that I'm testing out. It has two returns. Here is the code:
x = 5
y = 7
def test(w, z):
if w == 5 and z == 7:
print("good!")
w = 6
z = 12
return(w, z)
test(x, y)
Alright so, there's my test function. It takes 'x' and 'y' and it does some stuff with them, and then it changes them if both are equal to the numbers.
However, I might want to keep that information that 'w' became 6 and 'z' became 12. In this case, I want 'w's value to equal 'x's. Likewise with 'y' and 'z'.
Unfortunately, when I try what I had already learned from stackOverflow:
x = test(x, y)
print(x)
I would get (6, 12). How can I make it so that 'x' gets 'w's value and 'y' gets 'z's value?
Do like this:
x,y = test(x, y)

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

Resources