[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] idiom question

From: Peter Keller
Subject: Re: [Chicken-users] idiom question
Date: Sun, 6 Oct 2002 22:35:56 -0500
User-agent: Mutt/1.2i

On Sun, Oct 06, 2002 at 10:57:55PM +0200, felix wrote:
> What do you think? Any comments would be welcome.

I have some ideas:

Suppose we define some functions in terms of the srfi-4 vectors that make
it easy to use them with C FFIs?

(define make-intp
    (lambda x
        (apply s32vector x)))

(define intp-ref
    (lambda x
            ((= (length x) 1)
                (s32vector-ref (car x) 0))
            ((> (length x) 1)
                (s32vector-ref (car x) (cadr x)))
                (print "intp-ref: Incorrect number of arguments!")))))

(define intp-set! 
    (lambda (x . y) 
            ((= (length y) 1)
                (s32vector-set! x 0 (car y)))
            ((= (length y) 2)
                (s32vector-set! x (car y) (cadr y)))
                (print "intp-set!: Incorrect number of arguments!")))))

(define intp-length
        (lambda (x)
                (s32vector-length x)))

now, you can do things like this:

(define qux (make-intp 1 2 3 4 5 6))
(print (intp-ref qux))
(print (intp-ref qux 2))
(intp-set! qux 23)
(print (intp-ref qux))
(intp-set! qux 3 23)
(print (intp-ref qux 3))
(print (intp-length qux))

And get:

Sample code used in a real context:
(define bar (make-intp 68))

(let ((b (foobar bar)))
    (print b " " (intp-ref bar)))

results in:
68 69

The key here is that these functions will just "do the right thing"
depending how many arguments are passed to them. This allows for a simple
use for a function that just wants to fill in a variable by reference,
or a function that takes a whole array.

Now, it becomes (I think) as simple as it can get to pass these things
between C FFI funcalls. The main point was I wanted to disassociate
the s32vector from being the defacto int pointer that chicken uses,
cause if I ever want to make this code portable, I can just change the
abstraction of the intp ffi stuff to whatever the other compiler would
use. However, I don't think I'll be moving from chicken for a good long
time, maybe forever.  I just like it too much. Given that, I also wanted
it to be a simple as possible to write. (s32vector-set! x 0 y) was just
too damn much to do something simple(IMHO). In the code I'm writing,
I'm moving data from C to scheme and back again a lot, and (intp-set! x
y) is a lot easier if I know I'm only going to be needing one element
passed into the function.

If people like this idiom, I can do it for the rest of the chicken/C
types supported in srfi-4 and make it available as some extension package.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]