Archive for the ‘500 Programming Languages’ Category

Comic-Fu

Tuesday, February 9th, 2010
saveplace

Angie has been slaving away working on Company-Y lately, and I think it’s coming along quite nicely.

Yesterday I decided to give her a break by helping with the coloring of the latest page “I love it when a plan comes together”, and I realized that the coloring process could be greatly sped up if we could simply flood fill the various areas, rather than having to draw around the outline of the area before flood filling it.

The comic is drawn in The GIMP. The lines are drawn on an transparent layer, and then the coloring is done on another layer below, so as not to mess up the lines. Since there are no boundaries on the lower layer, flood filling doesn’t work.

So I tossed together a quick TinyLisp add-on which takes the current layer, duplicates it, thresholds on alpha level (gets rid of any pixels that aren’t within a certain opacity level), and puts the new layer below the current one. After that, flood filling can be done in the lower layer without any issues related to the antialiased/feathered edges of the lines.

It’s a fairly simple script, though it took me a while to get it all working correctly (why the heck do all the GIMP built-ins return lists, making me have to (car …) everywhere, instead of just the primitives?)

Anyway, I was inspired, and came up with some ideas for some more time-saving add-ons to write, so I’ve started a Comic-Fu project at GitHub

If you want to install it, simply download make-fillable.scm and put it into your .gimp-2.6/scripts directory. It should then be in the Filters->Comic-Fu menu the next time you start up the GIMP.

p.s. I’m totally counting this as one of my programs for my 500 Programming Languages thing. I’ll do a write-up of TinyScheme at a later point.

A brainfuck synthesizer

Thursday, August 6th, 2009

waves

For my latest in my series of 500 Programming Languages, I decided to write a (simple) synthesizer in brainfuck.

Introduction to brainfuck

brainfuck is an esoteric programming language based on the idea of making a language with the smallest possible compiler. Indeed, my Python brainfuck compiler is only 30 lines of Python code, and I’m sure there are some optimizations I could have done to make it shorter if that was my goal with the whole thing.

The only data structure you get is a single array (if it were infinite you’d have a good representation of a Turing machine), and all you can do is move around this array with a pointer, increment and decrement values, input and output values, and loop.

The entire language consists of 8 commands:

  • > move the pointer forward one cell
  • < move the pointer back one cell
  • + increment the current cell
  • - decrement the current cell
  • . output the byte in the current cell
  • , input a byte into the current cell
  • [ move to the matching ] if the current cell is zero
  • ] loop back to the matching [ if the current cell is non-zero

Anything other characters in a program are ignored, and thus comments can be inserted anywhere into the program. Just be careful not to type proper English sentences with commas and periods, or you might get some funny bugs until you realize what’s happening.

That’s really all there is to the language. There are a couple of areas of behavior that aren’t standardized between interpreters, relating to the size of the array, the cell size, and handling end-of-file when inputing. Those are covered in more detail on the brainfuck Wikipedia page.

So, since this is such a simple language (to comprehend, not to write in), and I already provided a working compiler in my previous post, I’m going to do this post a little differently, and just cover the process I went through in writing my first non-trivial brainfuck program.

The idea

I tried to come up with an idea for a program you don’t normally see implemented in brainfuck, and I’ve never seen anything done with brainfuck and audio, so I decided to write a simple (non-interactive) synthesizer.

My first brainfuck program

To start out with, I wrote a program to just generate one second of simple square wave, at 4kHz (the max for 8kHz sample-rate audio).

With 8000Hz audio, there are 8000 bytes per second, so if the wavelength is two bytes (one byte high, one byte low, makes a complete single wave), that makes the frequency 8000/2, or 4000kHz. If I doubled the wavelength, I’d get half the frequency, or 2000Hz.

set counter to four thousand
> ++++ four
[ > +++++ +++++ times ten
  [ > +++++ +++++ times ten
    [ > +++++ +++++ times ten
      [ <<<< + >>>> - ]
      < -
    ]
    < -
  ]
  < -
]
 
keep a zero value and generate a 255 value
>> +++++ five
[ > +++++ times 5
  [ > +++++ +++++ times ten
    [ <<< + >>> - ]
    < -
  ]
  < -
]
< +++++ plus five (255 total)
 
<<
[
  >> . output 255
  < .  output 0
  <
  - decrement counter
]

This demonstrates how even generating a large number in brainfuck is quite a chore. I had to use four nested loops and four different cells to calculate 41010*10. Still, it’s better than having 4000 plusses at the beginning of my program.

The way loops are done in brainfuck reminds me of doing loops in assembly language. In fact, brainfuck in general reminds me of assembly language, but without all those convenient opcodes you’re used to. :)

What’s your frequency, brainfuck?

Next, I wanted to generate a lower frequency, working my way toward taking user input to determine frequency.

I picked the A below middle C, which has a nice, even frequency of 220Hz. When you divide 8000 by 220, you come up with a wavelength of approximately 36. Half low and half high makes that 18 bytes per half, so I needed to update the previous program to output 18 bytes of each value instead of just one byte per value.

222 waves of 36 bytes each equals 8000 samples for 1 second of audio
> +++++ +++++ +++++ +++++ ++  22
[ > +++++ +++++ times ten
  [ << + >> - ]
  < -
]
++ plus 2 more
 
>> +++++ five
[ > +++++ times 5
  [ > +++++ +++++ times ten
    [ <<< + >>> - ]
    < -
  ]
  < -
]
< +++++ plus five (255 total)
 
<<
[
  >>>
  +++++ +++++ +++++ +++ eighteen up and down = 220Hz
  [
    < . output 255 byte
    > - subtract from counter
  ]
  +++++ +++++ +++++ +++ eighteen up and down = 220Hz
  [
    << . output 0 byte
    >> - subtract from counter
  ]
  <<<
  -
]

This version adds two extra loops and an extra cell to generate eighteen 255s and eighteen zeroes for each iteration of the loop.

Like MIDI, but crappier

So, the next and final step was to allow input of notes to play, and the lengths to play each of those notes.

I found a helpful reference on the frequencies of musical notes.

Due to the fact that brainfuck only allows you to read a single byte at a time, and because it made the program simpler over all, I decided to have the two values input for each note represent the length, in waves, and the length of each half-wave. This allowed me to use the basic structure of the previous program, and to support a wider range of frequencies without having to handle multiple-byte input for notes.

generate the 255 byte for output
>>> +++++ five
[ > +++++ times 5
  [ > +++++ +++++ times ten
    [ <<< + >>> - ]
    < -
  ]
  < -
]
< +++++ plus five (255 total)
<<
 
, read in the length of the first note (in waves)
> , read in the length of each half wave
[
  <
  [
    >
    [->>+>+>+<<<<] copy the value to two cells for use in the following loops plus an extra copy
    >>>>[-<<<<+>>>>] copy the value back to the original location
    <<
    [
      < . output 255 byte
      > - subtract from counter
    ]
    > goto next counter
    [
      < . output 0 byte (zeroed by the last loop)
      > - subtract from counter
    ]
    <<<<
    -
  ]
  , read in the length of the next note (in waves)
  > , read in the length of each half wave
]

Since the half-wave length is input from the user, I can’t simply re-generate the value each time through the main loop, so I had to make extra copies of the value, and then re-copy the value back to its original input location, since it’s zeroed out when it’s copied to the other location.

Like I said, it’s harder than assembly language.

Now all you have to do is fire up your favorite hex editor and create a binary file with a list of lengths and notes (for example mary.notes), and save the output from the program into a file (for example, mary.raw), and you will have your very own brainfuck-generated music!

In an 8-bit unsigned 8kHz mono raw PCM file. Linux users can use aplay to play this file. It just so happens the default format is the same as the output of this file. This also means you can pipe the output of this program directly into aplay, as well.

All you need now is some sort of front-end which will interactively take keyboard input and translate it into notes, and you could use this for live performances. (note: you probably don’t want to use this for live performances)

Learning more about brainfuck

I learned everything I know about brainfuck from the brainfuck Wikipedia page, and so can you!

Conclusion

This is probably not a language you want to use, like, ever.

Unless you’re a huge nerd, like myself.

Then you might want to, just for the fun of it.

If it doesn’t sound like fun to you, then you can safely say you’re less of a nerd than me.

500 Programming Languages: Python

Saturday, August 1st, 2009

sillywalk

Python is one of my favorite programming languages. It’s almost always the first one that I reach for when I have a programming task I’d like to try out, and often enough, it’s the final language of that task, too.

Introduction to Python

On the official Python website, Python is described as “a dynamic object-oriented programming languages that can be used for many kinds of software development.”

They also claim that “Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code.”

I am inclined to agree.

Though Python is a true “everything is an object” OO language, you can do more than just Object-Oriented programming with it. You can do plain-ol’ procedural programming, functional programming, Object-Oriented programming, and probably some other types of programming if you wanted.

One of the nicest things about Python is the “batteries included” approach, which means that Python comes with a ton of modules that do a large amount of what you want to do, right out of the box (or tarball, or installer…I don’t know if you can actually get Python in a box). Does your app need to write a cgi app? Or even better, a wsgi app? Web client? Web server??

Yep, it has all those, and many, many more.

There are many, more thorough introductions to Python out there, so I won’t attempt to cover the language in too much more depth, but I will show you a couple of things that really capture the spirit of Python:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance
>>> import this
The Zen of Python, by Tim Peters
 
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import __hello__
Hello world...
>>> 
</stdin>

My First Python Program

This is far from my first program in Python. I first discovered Python when I was in High School, so possibly as early as 1999-2000. I had discovered Blender, a free 3D editing application, and it had Python embedded within it, for use in creating extensions and scripting games for the built-in game engine. Back then, I still thought I was going to be a video game developer, so I made some effort to learn Python so I could write games in Blender.

Anyway, enough history. :)

For this program, I implemented a Brainfuck-to-Python compiler. I won’t go into Brainfuck right now because I will be doing a post on it next.

This program is nowhere near demonstrating all of, or even a large number of, Python’s features, but it does demonstrate how easy it is to write a quick-and-easy program.

I threw this compiler together in less than 5 minutes, and it functioned properly on my first try (the Brainfuck hello world from Wikipedia).

The only addition I had to make later was handling the case of end-of-file on the input.

def compile(program):
    indent = 4
    code = [
        'def compiled(input=None, output=None):',
        '    import sys',
        '    if not input: input = sys.stdin',
        '    if not output: output = sys.stdout',
        '    i = 0',
        '    a = [0]*30000'
        ]
    commands = {
        '>': 'i += 1',
        '< ': 'i -= 1',
        '+': 'a[i] += 1',
        '-': 'a[i] -= 1',
        '.': 'output.write(chr(a[i]))',
        ',': 'a[i] = ord(input.read(1) or "\0")',
        '[': 'while a[i]:',
        ']': ''
        }
    for command in program:
        line = commands.get(command, None)
        if line: code.append((' ' * indent) + line)
 
        if command == '[':   indent += 4
        elif command == ']': indent -= 4
    exec '\n'.join(code)
    return compiled

This function takes a string containing BF code as its one argument and returns a function which will run that code when called.

The function returned will have two optional arguments, input and output, which are expected to be file-like objects (at least implementing read and write, respectively), which allows for passing in specific input and/or handling the output from within a python program.

It’s kind of a dirty way to do it, building Python source, an then running it with exec, but it gets the job done. I could also save the function to a compiled .pyc file, so you could later import it directly, but that would require a bit more code and ruin the simplicity of it all. I could also have generated input for my Python assembler, and used that to generate a compiled .pyc file, but like I said, I was going for simplicity here, and encouraging people to learn Python, not necessarily Python bytecodes.

You can download the Brainfuck-to-Python Compiler if you’d like. You can download the Brainfuck-to-Python Compiler if you’d like.

continue on to learn more about Python

(more…)

The 500 Programming Language Challenge

Monday, July 27th, 2009

Are you a programmer? If so, then I have a challenge for you. I want you to become a programming linguist.

While making (somewhat slow so far) progress on my goal to program in 500 programming languages, it occurred to me that this could be a much more interesting project if I got more people involved.

I’m still aiming for my goal of writing about and in 500 different programming languages, but here’s my challenge to other programmers:

Write 500 different programs, in 500 different programming languages.

That’s it, that’s the whole challenge, well, with a couple of rules, I suppose:

  1. The 500 programs must be written after reading this post. No fair counting them if you’ve already (somehow) written 500 programs in 500 different languages, so they have to be new.

  2. The programs need to be semi-non-trivial. Something a little more advanced than “Hello, world.” To use one of my previous programs as an example, an implementation of the game of life is a semi-non-trivial program. Ideally the example will demonstrate some of the strengths of the language, as well.

  3. They languages used need to be different languages. It doesn’t count if you write in 500 different dialects of Basic, for example.

  4. Share your results with the world. Either post them on your own blog or put them on github, or whatever, just get them out there so other programmers can see and learn from them.

  5. Deadline: there isn’t one. Since this is a fairly long-term project, and I know varying people have varying amounts of free time for such a thing, I’m not putting any sort of cap on this. I’m shooting for 3 years or less to completion, but it could just as easily be a ten-year goal, or a one-year goal for someone particularly insane/enthusiastic.

  6. Winner: there also isn’t one. The idea is to encourage as many people as possible to do this. However, there is sure to be some recognition for the first one to accomplish the goal. I mean, seriously, how many people have written in 500 different programming languages?

So, it’s ok if you write some of them in languages you’ve written in before, but you need to write a new program, and it needs to at the very least do something more interesting than “Hello, world” or “99 Bottles of beer”

I’d love to see people take this challenge to an interesting extreme, such as writing a programming that does the same thing in 500 different languages, or writing only in esoteric programming languages.

I’ll put up a gallery and perhaps do interviews with/profiles of any developers who participate in the challenge.

Become a Programming Linguist

In my mind, there are 3 different kinds of programmers: the single-language programmer, the typical programmer, and the polyglot programmer.

The single-language programmer

This programmer is either very picky, very new to programming, or not someone who programs for a living. The latter two are acceptable, the former one really isn’t.

I would neither like to work with someone who refuses to program in anything but Haskell nor someone who refuses to program in anything but Visual Basic (though out of the two I’d pick the Haskell programmer).

If you’re new to programming, or don’t plan on doing it much, it’s acceptable to only know one language, but if you even only plan on writing Ruby On Rails or PHP web-apps for the rest of your life, you should probably at least know JavaScript and SQL as well.

The typical programmer

This programmer has learned a few programming languages, perhaps the Ruby/PHP, JS, and SQL mentioned above. This programmer knows everything they need to do their current job, and hopefully enough to do it **well*.

The typical programmer isn’t too afraid to pick up a new language when they feel a need to do so. Generally this need is brought up by work demands or growing tired of the language they use primarily.

Still, this programmer tends to stay away from “weird” programming languages, be they functional, stack-based, or simply something with an odd syntax compared to what they are used to. Such languages seem like they would be too much work to learn, without any practical benefit for this programmer who already has a good list of languages that do what they need.

With this self-inflicted limitation, the typical programming is truly missing out on some profound, powerful knowledge that they could gain if they even just took a little time to understand these foreign paradigms, let alone actually program in them.

The polyglot programmer

This programmer loves programming, and more importantly, loves programming languages.

The polyglot programmer doesn’t let as trivial a thing as “not needing to” prevent them from learning a new programming language. They seek out new paradigms and techniques and revel in their ability to apply what they learn from one language to a language they already know, thus making them a better programmer.

This programmer understands that there is a reason for every programming language design decision (even if that reason is “we didn’t think about it too much”), and can’t wait to try out a new language feature they’ve as-yet not encountered.

A polyglot programmer can apply for jobs that a typical programmer can only scoff at for requiring “one of those weird programming languages” that they could never be bothered to learn, and they can more quickly learn a new language that their current job might require because they have a better understanding of programming languages in general.

A programming linguist is basically a very-well-versed polyglot programmer, one who can pick up a new language in a day if there is any good documentation for it

The goal

The goal here isn’t to learn and become an expert at all of the 500 different programming languages. The goal is to be exposed to 500 different programming languages, to glean a bit of knowledge, to open one’s mind to new ways of looking at and solving problems, and to ultimately become a better programmer.

It doesn’t matter if after this, you never touch any of the 500 languages ever again, just the act of coming to understand the language enough to write a program in it will have altered your mind enough to make a lasting impact, especially for languages which are different from the “norm” of what you are used to.

Will you accept this challenge?

If so, let me know in the comments or an email.

If not, let me know why not. I’d love to hear from you either way.

Simplicity and Lazy Evaluation in A++

Wednesday, July 15th, 2009

After my last post on the A++ programming language, there was quite a bit of discussion on reddit about both a mistake I made about the classification of the language (which I corrected in my previous post), and questions about how A++ is different from Scheme.

Because of the relative simplicity of A++ compared to Scheme, rather than talk about how they compare and contrast (that would mostly be like, “Scheme does this, this, this, this, this, and this, whereas A++ does this”), I’m simply going to talk about the main aspects of A++, namely, its simplicity and the fact that it uses lazy evaluation.

The core of A++ is simplicity (and lambda-calculus)

The idea behind A++ is that it is lambda-calculus, with a simplified uniform syntax (using parens all the time, rather than only in certain cases), and with explicit name-binding added to it.

What this means is that everything is a function, with the exception of named constants, which enable a simple form of message-passing to be implemented. The only thing you can do with named constants is check if they are equal, so they add a very small amount of complexity to the language.

There are no data structures (that aren’t made up of nested lambdas), there are no primitive values, and no built-in operators, aside from those which allow the definition, binding, and applying of functions.

A tiny exception is made in instances when printing things out, but the only thing you can do a with a primitive is increment it, decrement it, or print it out, so it can’t be used in a program. Named constants also don’t count, since they essentially don’t have values. Ignoring these two trivial exceptions, there’s one main rule that A++ follows:

In A++, there are (pretty much) only functions.

The only (non-output-related) built-in operations are define, lambda, apply (which is done when the first thing inside some parenstheses isn’t “define”, “lambda”, or “equal”), and equal (which is used for comparing the aforementioned named constants).

To make A++ the powerful enough to write new language constructs within the language itself, it uses lazy evaluation.

Lazy evaluation

Parameter evaluation is done lazily, meaning an operation passed into a function is only applied (called) when you explicitly apply it (by wrapping it in a pair of parentheses).

This is needed in A++, because there are no built-in control structures. While loops aren’t strictly needed because A++ allows recursion, you do need some sort of conditional statement.

In A++, true, false, and if are defined as follows:

(define true   (lambda (x y) 
                 x))
 
(define false  (lambda (x y) 
                 y))
 
(define if (lambda (b t f) (b t f)))

Any predicate or boolean operation evaluates to either true or false, so when passed to if, it makes sense that only one of the two following parameters is evaluated.

If A++ used eager evaluation, both the t and f parameters would be evaluated before being passed into the if function, which, since A++ allows side-effects, could result in unwanted output. Even if A++ was purely functional, allowing no side-effects, it would waste time to evaluate both branches of the if function.

For example, if you were to run the following code:

(if true (ndisp! four) (ndisp! five))

you would get the expected output from A++ of

-->4

but if A++ eagerly-evaluated the parameters to if, you would end up with

-->4
-->5

instead (or possibly in the opposite order, depending on which evaluation order was used by the language).

Lisp offers deferred evaluation via the quote operator, and allows the construction of control structures with macros. Since the goal of A++ is simplicity, it makes sense that it would pick the lazy evaluation scheme, which allows it to fulfill both of those roles without any extra feature being added to the language.

This post is part of an ongoing series in which I am attempting to write about, and write programs in, 500 different programming languages, 500 Programming Languages

If you have any languages to suggest, or comments to make about this post, or the project in general, please don’t hesitate to leave a comment on this post or the main 500 Languages post.

The A++ Programming Language

Monday, July 13th, 2009

aplusplusimage

Introduction to A++

Update: Apologies to anyone who’s sensibilities were offended by the claim that A++ is a “purely functional” language. This was a mistake on my part. While the only thing (with the exceptions mentioned below) you can really manipulate with A++ is functions, you could perhaps say that A++ is a “purely function-oriented” language, but since it does offer destructive assignment it is not “purely functional,” but more of a baby-Scheme.

I’m going to go ahead and claim temporary sleep-deprivation-induced insanity, and offer a correction below.

Despite having the same name with just one more plus, A++ is not related in any way to A+. A++ is a truly tiny, purely functional programming language language where (almost) everything is a function, whereas A+ is anything but tiny and is far from being purely functional represents almost everything as arrays.

A++, which is short for Abstraction + reference + synthesis, is an abstraction of the lambda calculus, with a syntax that is even simpler (and thankfully contains only symbols which are on a standard keyboard). This simplicity is due to the fact that it borrows its syntax from Lisp and Scheme, requiring parentheses to surround each expression.

The addition that A++ makes to lambda calculus is the ability to explicitly assign names to objects (functions or values), something which lambda calculus only supports through binding via function calls.

A++ is intended to be a “learning instrument for programming” and thus doesn’t try to add any extensions to the language which would make it too useful for everyday programming.

Due to its simplicity, it is a great language for getting to understand concepts which would normally be overshadowed by all the other stuff in a language.

A++ is a Lisp-1, with a single name space for both functions and data. Indeed, in A++ there is no operator to define a function, one simply defines a symbol to map to a lambda expression.

Since A++ uses lazy-evaluation, control structures such as if statements and while loops can be created with just lambdas, without having to add macros to the language.

There are some primitive functions built into the interpreter to allow for converting church numerals into regular numbers, and for displaying booleans and numbers. There is support for primitive integers, strings, and symbolic constants. However, the support for primitive integers is limited to the minimum needed for converting from a church-encoded integer to a primitive integer, so the primitive integer can be printed, and the support for strings is only in place to allow for loading of external files into the interpreter. This means that in the language, you have to work exclusively with church numerals, and the only really useful primitive (aside from lambdas and define) are the symbolic constants.

All the standard lisp stuff, like car, cdr, map, filter, boolean operators (true and false, once again, defined in church encoding), various predicates (like nullp and zerop), while, and for-each are all built in the A++ language itself, and loaded automatically from a file when the interpreter is started, rather than being built-in functions.

So, when I said this was a purely functional language everything in this language is constructed using functions, I wasn’t kidding. The only difference from what most people would consider a purely functional language, is the fact that you can re-define a new value to the same name. Of course, without the ability to do this, closures would be of limited usefulness.

My First A++ Program

I had a hard time coming up with an idea for a program to implement in A++. Mainly, anything more complex I wanted to do, I couldn’t because of the very limited interaction with the outside world allowed by the A++ interpreter.

I looked at the list of solutions by programming task at Rosetta Code, and decided to implement the Roman Numerals task.

I based my solution off the first C solution for roman numerals. Due to the lazy-evaluation provided by A++, I was able to translate the macros used almost exactly.

While A++ makes possible functional and object-oriented programming, this example is imperative in nature, since it is copied more or less exactly from a C implementation of the same algorithm.

(define roman 
    (lambda(n)
 
      (define iftrue      ; standard if function requires an "else" bit
          (lambda(b t)
            (if b t nil)))
 
      (define digit 
          (lambda(loop num c)
            (loop (gep n num) 
               (lambda()
                 (print c)
                 (define n (sub n num))))))
      (define digits
          (lambda(loop num c1 c2)
            (loop (gep n num)
               (lambda()
                 (print c1)
                 (print c2)
                 (define n (sub n num))))))
 
      (define hundred (mult ten ten))
 
      (digit  while   (mult ten hundred) 'M   )
      (digits iftrue (mult nine hundred) 'C 'M)
      (digit  iftrue (mult five hundred) 'D   )
      (digits iftrue (mult four hundred) 'C 'D)
      (digit  while              hundred 'C   )
      (digits iftrue     (mult nine ten) 'X 'C)
      (digit  iftrue     (mult five ten) 'L   )
      (digits iftrue     (mult four ten) 'X 'L)
      (digit  while                  ten 'X   )
      (digits iftrue                nine 'I 'X)
      (digit  iftrue                five 'V   )
      (digits iftrue                four 'I 'V)
      (digit  while                  one 'I   )))

You can download the A++ roman numeral program if you’d like.

Sadly, A++ offers no way to build up a string for printing or to print multiple items on a single line, so each of the numerals will be printed on its own line.

Also, I chose this particular implementation because A++ doesn’t provide a function to perform division!

continue on to learn more about A++

(more…)

The A+ Programming Language

Saturday, July 11th, 2009

aplushead

I didn’t intend for it to take me a week to write this post, but I had some technical difficulties in getting started, which prevented me from even starting to learn the language until I solved them.

I expected to run into some problems getting things set up as I worked on this project, but I assumed most of those problems would be along the lines of getting the compiler and/or interpreter for a particular language to compile or run on my machine.

What I didn’t expect was to have so many issues just getting my text to be in the encoding that the language expects, but that is exactly what I ran into with A+.

Introduction to A+

A+ is a high-level language with a large number of primitive functions for manipulating arrays of data. It was created in 1988 at Morgan Stanley by Arthur Whitney, after he decided that none of the existing APL implementations would be suitable for their purposes.

A+ is a dialect of APL, and offers some extensions, such as a graphical user interface and inter-process communication, as well a module for storing and loading objects (functions, variables, and dependencies) and even a built-in database system.

Another feature A+ adds is the ability to set up dependencies between variables, so when a depended-upon variable is changed, the dependent variable changes as well. This allows for spreadsheet-like or reactive programming, with barely any effort. Actually, combined with the graphical display capabilities, you could actually pretty easily implement a spreadsheet in A+ if you felt like it.

Any dyadic (two-argument) function can be called using infix notation, which takes a little getting used to, especially with the right-to-left no order-of-operations precedence rules.

The language uses a healthy subset of the crazy hieroglyphs included in APL, and requires a special font for properly displaying the special characters. It’s also possible to use one of two ASCII-based modes when programming in A+, but where’s the fun in that?

After playing around with the language for a while, I can see why people enjoy APL and its derivatives so much. It’s one of those language where once you wrap your brain around it, it opens up new ways of solving problems that you’d never even considered before.

My First A+ program

lifescreen I decided on a (sort-of) graphical implementation of Conway’s Life, to demonstrate both the graphical system and the array-handling capabilities of A+.

This program is special because it’s not only my first A+ program, it’s my first program in an APL-like language of any sort.

You won’t be able to copy and paste this program directly and run it from A+, because I’ve converted the symbols to unicode in hopes of having them display properly in more browsers. If they don’t display properly, you can take a look at a screen-shot of the source code.

If you would like to run it, you can download the A+ life source.

$load s          ⍝ Load the graphical system
 
xy take2 m: xy[0] ↑ ⍉ xy[1] ↑ ⍉ m  ⍝ helper function to resize an array in 2d
n xr m: ⍉ n ⌽ ⍉m                   ⍝ helper function to rotate on the x axis
xy rot2 m: xy[0] ⌽ ⍉ xy[1] ⌽ ⍉m    ⍝ helper function to rotate in 2d
 
nextgen gen: {   ⍝ Calculate the next generation
        sums ← +/+/> (1;0;¯1) xr¨ 3⍴<>(1;0;¯1) ⌽¨ 3⍴<gen ;
        (gen ∧ 4=sums) ∨ (3=sums)
        }
 
cells ← ¯6 ¯6 rot2 15 15 take2 3 3⍴0 1 0 0 0 1 1 1 1 ⍝ start with a glider centered
`cells is `array
 
step c: .cells ← nextgen cells
step_button ← (step;cells)
`step_button has (`class; `button;
                  `title; "Step")
 
w ← (`cells;`step_button)     ⍝ Initialize our window
`w is `layout
`w has (`title; "A+ Life")
show `w

The most important function of the program is the “nextgen” function.

On the first line, reading from right to left, it does the following:

  1. Make an matrix containing 3 copies of the gen matrix
  2. Rotate each of those three copies verically by 1, 0, and -1 rows, respectively
  3. Make three copies of each of the three copies from the first step.
  4. Rotate the copies of copies horizontally by 1, 0, and -1 columns.
  5. Sum the rows and columns of matrices together into a single matrix.

On the second line, again, reading from the right to left:

  1. Get an matrix with any cell equal to 3 changed to 1, and any others changed to 0.
  2. Logically OR that matrix together with the array consisting of ones in the place of any 4s in the sums matrix, ANDed with the original gen matrix.

A more thorough explanation of the algorithm can be found at the APL wiki. You’ll notice that my version is quite different. That’s mostly because of difference in how the various build-in functions work in A+ and other APL implementations. That’s the same reason I had to implement the take2 and rot2 functions, since the A+ rotate (circle with a vertical line) and take (arrow pointing up) functions only allow you to rotate or take in a single dimension.

continue reading to learn more about A+

(more…)

500 Programming Languages

Monday, July 6th, 2009

I mentioned yesterday that I would be starting a series, talking about “some number” of programming languages.

Well, that number, as it turns out, it at least 500.

What?

I’m very interested in programming languages, but I’ve probably only ever written code in about 25 different languages, so I’m sure there’s some great language features and paradigms that I’ve never really tried. With this series, I aim to remedy this problem.

The goal of this project is to write a blog post about, and code in, every real programming language that I can get my hands on and a few of them which some might not call “real”, with an end goal of writing about and code in at least 500 different languages.

Based on languages I’ve found over the years, and the Wikipedia list of programming languages, there should be at least 500 languages I can get my hands on. There are at least 700 esoteric programming languages, but I will only be covering a few of those, like Brainfuck, LOLCODE, and Unlambda, since I want the posts of this project to be at least somewhat useful.

Why?

Aside from my own Pokémon-style reasons for wanting to do this project (gotta catch ‘em all!), I want to share information about programming languages with others.

The idea is for each post to be a sort of introduction and crib-sheet for the language it’s about, ideally enough information for someone to gauge whether or not they’d like to try this particular language out.

For older languages, it will be more of a history, since generally most people wouldn’t be interested in actually writing code in an old, dead language.

Also, I would love to see some conversation emerging around various languages, be it discussions of good and bad things about a particular language, or elaboration on parts that I may have overlooked.

The Plan

For each language, I plan on doing the following:

  • Write a summary of the language, including who created it, what it’s main uses might be, what paradigms it supports or encourages, and any other tidbits about the language itself.
  • Cover the anatomy of a basic program in the language.
  • Write a somewhat non-trivial program in the language. This I will only do for languages which I can get a running compiler or interpreter for. I’m not going to spend any money on this, so I will most likely not write any code in strictly-commercial languages or ones which would require me to buy an IBM mainframe to run.
  • Cover where and how to get and set up the language. If a language is particularly hard to find and/or get compiling, I’ll include information on how I got it and got it set up.
  • List plenty of links to language resources (for languages which have plenty of resources). I am by no means going to give a complete, exhaustive look at each language, so for those who are interested I will give you links to wherever it is that I think you can get more in-depth information.
  • Anything else that seem appropriate at the time.

If anyone can think of anything else they would like me to add to this list, please let me know. I really want this to be a project for others, not just me, so I’ll be glad to get any feedback anyone has.

The List

For those who are interested in which languages I’m planning on writing about, the tenative list is below.

If you know of a programming language that is not on the list, please let me know and I’ll add it. There are currently 518 languages on the list, but I know that I won’t be able to get my hands on some of them, so I’d like to be sure that I have at least 500 that I can get my hands on.

As I have time to do so, I will update the list to include links to the most relevant page about each language, and as I publish each post I will add a link to the post in the list as well.

I will be going through the list in lexicographical order, so first up: A+

And now, without further ado, the list:

(more…)