12 votes

Favorite function you've written?

What's a function you've written that you're particularly proud of? Maybe it saved a business, or maybe you just think it's neat.

14 comments

  1. [3]
    teaearlgraycold
    Link
    Here's a small function from a Game of Life implementation that checks how many adjacent cells are alive: /// Count living cells adjacent to a cell in the matrix. #[inline] #[rustfmt::skip] fn...

    Here's a small function from a Game of Life implementation that checks how many adjacent cells are alive:

    /// Count living cells adjacent to a cell in the matrix.
    #[inline]
    #[rustfmt::skip]
    fn alive_neighbors(&self, x: i32, y: i32) -> u8 {
        [
            self[(x - 1, y - 1)], self[(x + 0, y - 1)], self[(x + 1, y - 1)],
            self[(x - 1, y + 0)], /*  selected cell  */ self[(x + 1, y + 0)],
            self[(x - 1, y + 1)], self[(x + 0, y + 1)], self[(x + 1, y + 1)],
        ]
        .iter()
        .fold(0, |total, &neighbor| total + (neighbor != 0) as u8)
    }
    

    I really like how it lays out the search for adjacent cells in a semi-graphical manner. It's also a great example of how auto-formatters shouldn't be applied universally. Not all code is "just code" where layout is meaningless.

    15 votes
    1. [2]
      vektor
      (edited )
      Link Parent
      This is the kind of stuff why I kept fighting with my law Prof about code sometimes (but really only sometimes) being genuinely deserving of copyright protection as a work of literature. In German...

      This is the kind of stuff why I kept fighting with my law Prof about code sometimes (but really only sometimes) being genuinely deserving of copyright protection as a work of literature. In German law, copyright is quite freely given to works of art and works of literature, kind of similar to the US. Copyright protection for code is slightly weaker, but given slightly more freely. The key phrase is that literature needs to be a "personal mental creation" and code needs to be a "individual mental creation"; in consequence, this means that we're not looking to find your personality in your code, because it's mostly about modestly creative solutions to a requirement satisfaction problem. Code therefore merely needs to be "your own creation".

      Now, I'm not sure whether a dogmatic view at the current German copyright law would even allow it, but I'd argue that sometimes code is entitled to both protections. (A dogmatic alternative would be that the section on code is more specialized and therefore eliminates the applicability of the general section to code.) I think my Prof was of the opinion that general copyright was in principle applicable, just that code never (or extremely rarely) rises to the required level. Your snippet is, imo, proof that code can go beyond boring solutions and into the realm of literature, irrespective of whether one believes that code actually reaches that level.

      Congratulations, you've created a legal clusterfuck, because I've got no clue how those pieces of law interact if you try to apply them both. If one grants you an exclusive right with no exceptions, and the other grants you the same right with an exception, does the exception apply or not?

      3 votes
      1. Moonchild
        (edited )
        Link Parent
        Perhaps I am jaded (well, no, I am definitely jaded) but that snippet does not seem especially beautiful to me. I have seen other expressions of the game of life which I find much prettier and...
        1. Perhaps I am jaded (well, no, I am definitely jaded) but that snippet does not seem especially beautiful to me. I have seen other expressions of the game of life which I find much prettier and more expressive of deep identities.

        2. I think the assignment of copyright to such code is similarly fraught to the assignment of copyright to mathematical formulae (which can unarguably also be called beautiful).

        1 vote
  2. bub
    Link
    Not my original invention (though I've "written" it many times), but I've always loved the elegance of a sign function like this: int sign(int x) { return (x > 0) - (x < 0); } It's very "essence...

    Not my original invention (though I've "written" it many times), but I've always loved the elegance of a sign function like this:

    int sign(int x) {
        return (x > 0) - (x < 0);
    }
    

    It's very "essence of C."
    And of course, it doesn't have to be int. Just used that example for simplicity.

    9 votes
  3. Eric_the_Cerise
    Link
    Any and all recursive functions. The day I learned about them, and wrote my first one and watched it work just blew me away. Same feeling with boot(-strapping) computer OSes, bootstrapping...

    Any and all recursive functions. The day I learned about them, and wrote my first one and watched it work just blew me away. Same feeling with boot(-strapping) computer OSes, bootstrapping compilers, etc. They are like the programming world's version of perpetual-motion machines, except they actually work.

    5 votes
  4. Apos
    (edited )
    Link
    When I coded my first game, I didn't yet know functions were a thing. I coded the mau mau card game putting all the code into an infinite while loop in the main function in Java. I coded all the...

    When I coded my first game, I didn't yet know functions were a thing. I coded the mau mau card game putting all the code into an infinite while loop in the main function in Java. I coded all the features using an intricate state machine, it even had an AI. The whole main function was 600 lines.

    Edit: Apparently I also didn't know about boolean variable! I used ints with 0 for on and 1 for off.

    Edit2: I ported the code to C#. Used Egyptian braces instead and it's down to 377 lines. ;)

    4 votes
  5. onyxleopard
    Link
    Many years ago I cam across this fairly elegant implementation of generating n-grams in Python. I rewrote this to be totally lazy using some of the facilities of Python's itertools module: def...

    Many years ago I cam across this fairly elegant implementation of generating n-grams in Python.

    I rewrote this to be totally lazy using some of the facilities of Python's itertools module:

    def ngrams(iterable, n=1):
        """Generate ngrams from an iterable in a totally lazy fashion
        
        l = range(5)
        list(l) -> [0, 1, 2, 3, 4]
        list(ngrams(l, n=1)) -> [(0,), (1,), (2,), (3,), (4,)]
        list(ngrams(l, n=2)) -> [(0, 1), (1, 2), (2, 3), (3, 4)]
        list(ngrams(l, n=3)) -> [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
        
        """
        from itertools import tee
        from itertools import islice
        yield from zip(*(
            islice(items, i, None) for i, items in
            enumerate(tee(iter(iterable), n))
        ))
    
    4 votes
  6. [3]
    Moonchild
    (edited )
    Link
    This. It is a toy—not practical at all—but it is a compacting garbage collector in 7 lines of code!

    This. It is a toy—not practical at all—but it is a compacting garbage collector in 7 lines of code!

    3 votes
    1. [2]
      teaearlgraycold
      Link Parent
      J looks like a competent version of brainfuck. How fast is it?

      J looks like a competent version of brainfuck. How fast is it?

      1 vote
      1. Moonchild
        Link Parent
        J is nothing like brainfuck. It is quite fast in general; but that interpreter is for lisp, which means pointer-chasing, which is not something it is good at. The GC specifically is ok, though it...

        J is nothing like brainfuck.

        It is quite fast in general; but that interpreter is for lisp, which means pointer-chasing, which is not something it is good at. The GC specifically is ok, though it does a lot of redundant work at the moment, and there is some space overhead.

        4 votes
  7. mat
    Link
    ArrayFormula(ROUNDUP(IF(D4:D="Y",IF(C4:C="Adult",Summary!$C$8,IF(C4:C="Youf",Summary!$C$9)),0) + IF(E4:E="Y",IF(C4:C="Adult",Summary!$C$8,IF(C4:C="Youf",Summary!$C$9)),0) +...
    ArrayFormula(ROUNDUP(IF(D4:D="Y",IF(C4:C="Adult",Summary!$C$8,IF(C4:C="Youf",Summary!$C$9)),0) + IF(E4:E="Y",IF(C4:C="Adult",Summary!$C$8,IF(C4:C="Youf",Summary!$C$9)),0) + IF(F4:F="Y",IF(C4:C="Adult",Summary!$C$8,IF(C4:C="Youf",Summary!$C$9)),0) + IF(G4:G = "Y",10/3,0) + IF(H4:H = "Y",10/3,0) + IF(I4:I = "Y",10/3,0),0)) 
    

    No, there isn't any nice formatting. I'm not sure I'd say this is my favourite function but it's certainly one which I was very happy to get working and step away from. It's from a Google Sheets document and while I know in the grand scheme of things it's pretty simple it is, by a very long way, the most complicated thing I've done with a spreadsheet (I went to one 2hr class about Excel 20 years ago and that's about my entire exposure to them). It was for a group event where costs varied depending on whether the attendee was a youth or an adult, and on how many nights they were staying. It calculates per-person cost.

    Took me a good 3-4 hours of swearing to get it working. I'm pretty sure I could have written a python or JS plugin that did the same thing in less time, but some masochistic part of me wanted to push through and get it done in what I assume is some sort of VBA. This is the refactored version where I managed to take out a good half of the awful nested IF clauses.

    I never want to use a spreadsheet again.

    3 votes
  8. Omnicrola
    Link
    I don't have an example on hand, but my favorites have always been the recursions. Usually to retrieve some data that's stored in a tree structure (like XML, or finding components in a UI layout)....

    I don't have an example on hand, but my favorites have always been the recursions. Usually to retrieve some data that's stored in a tree structure (like XML, or finding components in a UI layout). They're usually pretty simple, but provide a lot of utility and I find them particularly satisfying to write.

    2 votes
  9. Wulfsta
    Link
    I have a few that come to mind, but I particularly like this post order iterator for arbitrary trees.

    I have a few that come to mind, but I particularly like this post order iterator for arbitrary trees.

    2 votes
  10. satotake
    Link
    Number conversion (translation) function. Numeric systems differ between (natural) languages. Function to translate one (English) into another (Japanese). e.g. 1234000 <=> 1 million 234 thousand...

    Number conversion (translation) function.
    Numeric systems differ between (natural) languages.
    Function to translate one (English) into another (Japanese).
    e.g.
    1234000 <=> 1 million 234 thousand <=> 123万4千
    It is trivial but I reuse this so frequently.
    Some programming languages offer similar functions officially though.

    2 votes