Random REBOL snippets: Cookie reader, Closures
November 28th, 2008I posted a read-ff-cookies function in previous post. So I got a function that does what I used REBOL’s native read function for usually. But this one would send a cookie and behave more like FF.
It was used like this:
my-cookies: [ [ "cookiename" "a%3A2%3A%7Bs%3A11 %3A%22autologin..." ] ] read-ff-cookie http://theurl cookie-str my-cookies
I provide cookie data as a series and it uses this func to turn it into proper cookie string:
cookie-str: func [ cs ] [ r: "" foreach c cs [ append r join c/1 [ "=" c/2 ";" ] ] r ]
It turned out I needed to call this sort of read on multiple locations of my crawler script and making cookie data global and passing it in each time didn’t look that good. So I made a make-cookie-reader that produces my read function with a cookie already “embedded” / enclosed.
make-cookie-reader: func [ c ] [ func [ url ] [ read-ff-cookies url cookie-str c ] ]
This function returns a function that takes just one argument (url) and uses the c (cookie) argument from the time of creation of the function. We can create our own read function:
my-read: make-cookie-reader my-cookies
Now I can use my-read with just the url parameter anywhere in code that I need it. Basically I just replaced all calls to read with my-read.
—
This is called closure. It worked for my case but I found out that if I would make two read functions using the make-cookie-reader the second one would change the first one too, which is not what we want. I went googling a little and found out few things:
Rebol 3 (now in the making) will natively support closures:
make-cookie-reader: closure [ c ] [ func [ url ] [ read-ff-cookies url cookie-str reduce [ c ] ] ]
Even more interesting thing.. I found the page of Ladislav, where he posts some MEGA AWESOME rebol libs. Well libs that can do what your ordinary language libs can only dream of doing. Like support for closures with the same syntax you see above in R2, custom control structures (cfor, pif), tailfunctions, currying, function inheritance?!, to name just few!
cfor [num: 0] [num <= 30] [num: num + 1] [
if num = 15 [recycle]
print num
]
pif [
negative? x [-1]
zero? x [0]
true [1]
]
f: tailfunc [x [integer!] y [integer!]] [
print x
either x >= y [y] [f x + 1 y]
]
There are also some extensive docs. I could take a week off to just explore that page and code on it! This will be probably my last post on REBOL for a while because the crawlers are mostly done now.

![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=ec552030-ea58-4328-8408-1cb5be7e13c6)
December 1st, 2008 at 4:38 pm
I hope R3 will get to a usable state soon! I can’t wait much longer.