Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Created May 27, 2011 22:02
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 dharmatech/996274 to your computer and use it in GitHub Desktop.
Save dharmatech/996274 to your computer and use it in GitHub Desktop.

Block expressions in various languages

What is a block expression? I'll give an example of what it might look like if it were allowed in C:

int a ;

a = {
        int b ;
        int c ;

        b = 10 ;
        c = 20 ;

        return b + c ;
    }

Of course, that's not legal.

A block indicates a group expressions which are executed in sequence, possibly in a new scope. The value of the last expression is returned.

Some languages allow blocks as expressions.

Scheme

(define a (let ()
            (define b 10)
            (define c 20)
            (+ b c)))

Perl 5

my $a = do { my $b = 10 ; my $c = 20 ; $b + $c } ;

GCC

#include <stdio.h>

int main ()
{
    int a ;

    a = ({ int b = 10 , c = 20 ; b + c ; }) ;

    printf ( "%d\n" , a ) ;

    return 0 ;
}

See the section 6.1 of the GCC manual for more details.

Ruby

a = proc { b = 10 ; c = 20 ; b+c }.call()

Languages that don't allow block expressions

Python

@glenjamin
Copy link

In ruby you can actually just do:

a = begin
  b = 10
  c = 20
  b+c
end

@dharmatech
Copy link
Author

Thanks glenjamin!

@dharmatech
Copy link
Author

@glenjamin I left in the first Ruby example as that one runs the block in a new scope.

@glenjamin
Copy link

The ruby example is actually just defining a function, then evaluating it and storing the return value, which to me doesn't seem to be the same thing as a block expression, if you're allowing this then in python you could do:

def __throwaway():
b = 10
c = 20
return b+c
a = __throwaway()

However in all of these cases when you're using a block expression, you should probably be asking yourself "why isn't this just a private method?"

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