Archive for April, 2009

Reading files in factor

Working code for the impatient

The following factor code reads and counts the number of words in the file “/etc/fstab”

USING: io.encodings.ascii io io.files prettyprint splitting sequences ;
"/etc/fstab" ascii file-contents " \n\t" split length .

See also

Official api docs.

Add comment April 10, 2009

De-nesting decorators in python

Definitions of decorators are quite nested

def decorate(f):
    def patched(*args, **kwargs):
        # do stuff involving f
    return patched

About 25% I also forget to write the final “return patched”.

One way to work around this is to write a ‘denest decorator decorator’ so you can write the following as an alternative to the above:

@denest
def decorate(f, *args, *kwargs):
    # do stuff involving f

This has the disadvantage that you can’t perform operations at the time of decoration – but it simplifies code slightly for the standard case (at the cost of making your code less idiomatic).

The denest decorator is defined like this:

def denest(func):
     def decorate(f):
           def patched(*args, **kwargs):
               return func(f, *args, **kwargs)
            return patched
     return decorate

Example usage:

A decorator that converts converts a function which could raise an Excpetion into a function which returns None on error.

@denest
def makeIntoTry(f, *args, **kwargs):
    try:
        return f(*args, **kwargs)
    except Exception:
        return None

Add comment April 6, 2009


Meta

Facets

abstruse Add new tag AOP apt aspect oriented programming assumes knowledge autiobiographical bash scripts bell books clarity code samples configuration console emacs for the benefit of google functional programming graphical design hacks higher-order functions howtos intention revealing programming keyboard links linux note to self opinions parsing patterns philosophising philosophizing programming python random ideas refactoring removing packages short stories succinct svn systems stuff theoretical philosophizing typing work ethic you probably don't want to read this

Archives

Pages

 

April 2009
M T W T F S S
« Mar   May »
 12345
6789101112
13141516171819
20212223242526
27282930