Skip to content

Instantly share code, notes, and snippets.

@randomphrase
Created April 29, 2015 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randomphrase/cacf91a608b83324f4bd to your computer and use it in GitHub Desktop.
Save randomphrase/cacf91a608b83324f4bd to your computer and use it in GitHub Desktop.
Example how bash function input/output can be used to compose
#!/bin/bash
# Creates an XML element from the first parameter. Remaining parameters and all stdin are copied to stdout.
function elem() {
local name=$1
echo -n "<$name>"
shift
echo -n $*
[[ ! -t 0 ]] && cat
echo "</$name>"
}
function title() {
elem "title" $*
}
function author() {
elem "author" $*
}
function book() {
elem "book" $*
}
function library() {
elem "library" $*
}
{
{
title "Moby Dick"
author "Melville"
} | book
{
title "Das Capital"
author "Marx"
} | book
{
title "The Cat In The Hat"
author "Suess"
} | book
} | library
@ap
Copy link

ap commented Mar 31, 2016

I guess the Python version would look like this:

def elem(name, content=[]):
    return ["<%s>" % name] + content + ["</%s>" % name]

def title(content):
    return elem("title", content)

def author(content):
    return elem("author", content)

def book(content):
    return elem("book", content)

def library(content):
    return elem("library", content)

print "".join(
        library(
            book(
                title(["Moby Dick"]) +
                author(["Melville"])
            )
            + book(
                title(["Das Capital"]) +
                author(["Marx"])
            )
            + book(
                title(["The Cat In The Hat"]) +
                author(["Suess"])
            )
        )
    )

Simpler but less DSLish, I guess.

@randomphrase
Copy link
Author

Still very readable - I like it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment