Learning Java and a Scheme program

April 16th, 2009

In answer to my last post I encountered this interesting snippit:

Can you figure out what it does? Why it does it?
  1. (let* ((yin ((lambda (foo) (newline) foo)
  2.              (call/cc (lambda (bar) bar))))
  3.        (yang ((lambda (foo) (write-char #\*) foo)
  4.               (call/cc (lambda (bar) bar)))))
  5.  (yin yang))

In other news, due to this that and the other, I have to learn Java.  So far, I’ve not learnt much.  I’ve found out two interesting things.  First, threads are remarkably easy to make.  Now, I’ve never done threading before, so I’m wondering how easy it is to do in other languages I’ve used.

Second, Java code is far too long.  I’ve always been annoyed with “code generation” features for just this reason.  If you need to generate code, you’re doing something wrong, IMO.  Code completion, (as in function parameters and variable names) is fine since that’s for human legibility and saves typing.  But generating whole skeletons?  Puh-lease.

Kinda turned me off C# before I took a good look at it (one of these days, I tell you).

Reading code

April 8th, 2009

I’ve recently resolved to start reading other peoples’ source code.  However, I’ve noticed that everything I have sitting around falls into four categories.

  1. Stuff I wrote (not much)
  2. Stuff too large to read (i.e. Mozilla, Pidgin, OpenOffice  and most other things I use)
  3. Something closed-source (i.e. mu torrent, K media player, Abyss webserver)
  4. Something I hate (not much I haven’t deleted.  I’m tidy like that.)

So, if anyone has some not-too-big code they recommend I’d love suggestions.  Stuff you wrote is cool.  Stuff you didn’t write is cool.  Open source things you contributed a bit to is cool.  Stuff in C is cool.  Stuff in LISP is cool.  Stuff that’s elegant is cool.  Stuff that’s buggy and kludgy is cool.  Whatever.  As long as I can read it in a few days.

Boy’s first library

January 10th, 2009

I’m currently working on a discrete, finite probability library.  It’s progressing fairly well.  The only downside to the library, as I’m beginning to realize, is that most probabilities, even discrete ones, are not in a finite number of categories.

However, here’s some examples of what the library can do.

  • All calculations are exact.
  • You can model dice.  I wrote a dice function that rolls 2d6, 3d6, 1d4, 27d27, etc.  I also modeled a few systems I like (for instance Dungeons and Dragons’ 4-die ability roll).
  • You can transform a function.  For instance, you can take a hero’s ability score in D&D, subtract 10, divide by 2, and round down to get the distribution of modifiers.
  • You can combine distributions using a function.  For instance, given 2d6 and 3d4, you can find the distribution of 2d6+3d6.  More interestingly, you can find the distribution of those two combined using any function whatsoever (for instance, multiply and take the square root, to get the geometric mean).  If the function returns a distribution itself, this can let you do some tricky things like have distributions of distributions (which the library of course has a ‘compose’ function for if you didn’t want that).
  • You can make a uniform distribution out of an arbitrary set of things, which is often a helpful starting point.  You can give the library a list of things and their probabilities, but since that’s how the library stores distributions, that’s a little boring for me.
  • If the distribution is all numbers, you can get the mean, median, quartiles, a cumulative version of the distribution.
  • You can make a random generator out of a distribution (for instance, given the d6 distribution, make a function that returns a random number 1-6 whenever called).
  • You can plot numerical distributions (approximated by a polynomial, too.) and their cumulative versions along with boxplot stats.  This doesn’t return anything, it just dumps a bunch of pretty graphs and statistics.

This is my to-do list for the library:

  • Standard distributions like the binomial distribution
  • Standard deviation and variance
  • Fix - the ‘window’ of the graph is determined by the points in the distribution.  It should also take into account the approximating polynomial, which can go off screen at present.
  • Fix - the random number generators made my polynomials are almost certainly subject to rounding errors at present.  Change that.
  • Add permutations, and the standard distributions of permutations
  • The ultimate goal - a scheme macro, dist-random, which would do something like the following:

(dist (+ (dist-random 1 2 3) (dist-random 1 2 3)))

Which would return the distribution 2d3.  This would allow you to take a normal program that uses random generation, replace the random generators with dist-random, and wrap the whole thing in dist, and get back the distribution of outputs that program *would* have given is dist-random were actually a random number generator.  For instance, you could take a poker program that draws a hand of five cards and tells you what you got, and use this library to wrap it such that you just got a distribution of the hands in poker.  Remember too, that these are all exact probabilities.

If you have comments or suggestions, please contact me.  I’d especially like to hear anything you think I should add to the library.

Blog maintenance, Untitled python roguelike nears completion

January 4th, 2009

After having deleted about 3000 comments over a few weeks, none from humans, I decided to add a CAPTCHA system to the blog.  For those unfamiliar with the name, these are systems wherein the system presents a word or two to the user as a distorted graphic, and the user types the word correctly.  They are designed to be solvable by users and not computers, but have the downside of being irritating to the user by slowing everything down, and sometimes so distorted that humans can’t easily solve them either.  For this blog, I decided on a system called reCAPTCHA, which uses actual scanned text from a central repository.  It has the neat benefit of simultaneously recognizing scanned text that scanners can’t read, i.e. for digitizing books, while providing insurance against spam.

On a happier note, the mysterious python project I mentioned earlier is close enough to finished that I’ll elaborate more now.  I have been working on a roguelike game.  Since it’s an unpopular genre, many readers may not have heard of it before.  In a roguelike, the player moves around an ascii character inside a tile-based map, fighting monsters and picking up treasure.  They’re essentially like old-style block-based RPG games set in a dungeon, except the whole thing’s overhead and in ASCII instead of fancy graphics.  For instance, a ‘$’ might represent a pile of gold, or an ‘r’ the ever-feared rat.

In my game, the player must delve into a dungeon, collect as much loot as possible, and leave–a typical goal.  It includes line-of-sight, twenty-something identical monsters of increasing power, a random dungeon generator, about eight unique items, a message system, color (provided with python’s curses), and three original game devices.  The only aspects of the game uncompleted are the highscore table, and game balancing issues.  (Right now it works as a program, but it’s not much fun to play.)  Documentation might be added at some point.  If you intend to play the game, I advise you skip the next paragraph where I spoil the hell out of it.  Or read it, depending on your play style.

The first element is a branching dungeon.  As the player descends, she travels through an inverted “tree” about six levels deep.  This isn’t completely random, to make other aspects of the game consistent between plays.  Each level of the dungeon has a random setup of nine rooms connected by corridors, all in a grid, as per the classic ‘Rogue’ which started the genre.  There are a guaranteed nine monsters and nine items per level, for consistency between sessions.  The second element is lava.  As the player explores the dungeon, she may discover that it is in fact a volcano about to erupt–and she had better get out of the way before it does!  This provides a built-in time limit, an interesting forced aspect to exploration, and the opportunity for me to have fun making the lava flow up and down branches in a fluidlike manner.  Lava flow rate, relative to the speed of the player, is one of the balance issues I am working on now.  Finally, the goals of the game are rather like a checklist.  First, getting out of the dungeon alive is a plus.  Second, getting more points by taking items and killing monsters than the lava consumes provides an interesting ultimate goal.  Third, there are special items in the dungeon the player can try to get before she leaves.  There is gem on each of the six levels of the dungeon.  Getting all six gives the player a reward.  Also, there is a magic scroll in a special level somewhere in the volcano.  This is especially difficult to bring to the surface.

In all, I tried to make a simple, but fun roguelike to play in half an hour to an hour.  I wanted it to be original enough to be interesting, but simple enough that I could write it and fairly casual players could discover everything about it.  Finally, I wanted to write a game I myself would find fun to play, which I believe I have.

Euler problem 25

November 21st, 2008
  1. ;What is the first term in the
  2. ;Fibonacci sequence to contain 1000 digits?
  3. (define (square x) (* x x))
  4.  
  5. (define (pow man exp)
  6.   (cond
  7.     ((= exp 0) 1)
  8.     ((< exp 0) (/ 1 (pow exp (- man))))
  9.     ((even? exp) (square (pow man (/ exp 2))))
  10.     ((odd? exp) (* man (square (pow man (/ (- exp 1) 2)))))
  11.     (else #f)))
  12.  
  13. (define (prob25 digits)
  14.   (let ((big-const (pow 10 (- digits 1))))
  15.     (let fib ((first 1) (second 1) (count 1))
  16.       (if (>= first big-const)
  17.           count
  18.           (begin
  19.             ;(display first) (display " ") (display count) (newline)
  20.             (fib second (+ first second) (+ count 1))
  21.             )))
  22.     )
  23.   )
  24.  
  25. (prob25 1000)

Coding C

November 13th, 2008

I’ve been taking a break from my other projects to learn C. Since I already know C++ fairly well, this is most fun when I write hideous C involving pointer arithmetic. Right now I’m writing an interpreter (or more accurately I’m starting by writing a tokenizer, which isn’t working yet and which I may not choose to go past.

More importantly, I’m doing the whole thing over ssh on a BSD box, thus learning *nix at the same time. Since I used about three commands, I’m not learning *much* but there you go.

Euler Problem 1

November 3rd, 2008

I’ve decided to do a series of posts with my solutions to the Euler problems. They’ll be tagged with “euler”, and once I figure out how I’ll stop them from showing up on the main page.

This is the first Euler Problem
  1. (define sum
  2.   (lambda (x) (apply + x)))
  3. (define product
  4.   (lambda x (apply * x)))
  5. (define sum-1-to-n
  6.   (lambda (x) (* (/ 1 2) x (+ x 1))))
  7. (define (1+ x) (+ x 1))
  8. (define (-1+ x) (- x 1))
  9.  
  10. (let
  11.     ((smalllist '(3 5 6 9 10 12 15))
  12.      (num15s (quotient 1000 15)))
  13.   "(* num15s 15) -> 990, so we add the last few by hand"
  14.   (+ (* 15
  15.         (length smalllist)
  16.         (sum-1-to-n (-1+ num15s)))
  17.      (* num15s (sum smalllist))
  18.      993 995 996 999))

Continuing project, programming contest, perl

November 2nd, 2008

The project I’m working on I briefly mentioned last post is a deliberately simple roguelike set in a branching dungeon. It’s 60-70% done at current, and I’ll say no more until I at least get to final bugfixing.
I went to the ACM programming contest, in which our school placed very average. I had more fun that I expected from the day before and less than from the week before. I had lots of delicious free food. I’d do it again, overall, and be more interested in doing so if I knew my team well ahead of time.
I started learning perl, which looks exactly as disgusting as everyone says it is. It seems useful. It has very odd array/hash behavior which relate to its origin in string processing. An array of three arrays is just the contents of each of those three. To make the kind of thing I want, you need to make explicit reference variables. Interestingly, the fact that you can only pass one array (because they’re flattened) to a function means that everything is passed by value to functions. To my knowledge this is also true of the assignment operator. Since perl as I mentioned supports references, this is to my liking… the array flattening less so.

Regular expressions are as always kickass, and I understand perl’s engine is the best to be found. I really need to get a Linux system soon so I can do fun things like use the “grep” command or have very large text consoles.

Python and a new project

October 22nd, 2008

This past month I’ve been learning python. I wanted to see what all the hype was about. As it turns out, it’s actually justified. I don’t feel like python is a fundamental improvement over imperative langauges like C++ , php, and Java that I already know, but it’s more streamlined. The language design is obviously excellent. The code is easy to read. For example, the if statement is

if b==0:
    print "Divide by zero
else:
    print a/b

you get used to the forced formatting. It’s definitely worth it to have shorter, nicer-looking code. Debugging: b=0 is not a legal conditional. You don’t have to declare variables, but you do have to assign somethint to them before passing them to a function, etc. The compiler will usually catch something like:

abc=12
print fibbonacci(abbc)

The exception to this rule is attributes of objects. Objects can have attributes added dynamically, so it doesn’t work. My pet peeves so far: Python has some behavior toward global variables I still can’t figure out. Lambda expressions are not lambda functions, but they’re similar enough I expected them to be. They raised by expectations and dashed them. You can pass functions as objects, make them at runtime, etc. You just have to name them. So I don’t like the keyword “lambda”, although I admit I have no better alternative. Similarly, there’s a while..else and for…else that do not do what I would expect. Default functions for arguments and default values for objects are only initialized once. For instance,

function cache(item, array = []):
array.append(item)
print array
cache(1) --> [1]
cache(2) --> [1, 2]

This probably slightly optimizes the resulting program but it’s counterintuitive. My last gripe, and one that seems a language standard (for instance this annoyed me about Java), is the following: assignment is inconsistent. Numbers and get copied by value, objects and collections get a reference copied. I’d like to see designers go with a deep copy, shallow copy, or reference for EVERYTHING sometime, so I don’t have to check types when I’m doing an assignment, particularly in a dynamically-typed language like Python. However, deep and shallow copies are available as probably-can-do-it functions in a standard python module. Overall, Python seems like an amazingly relaxing language to program in (from someone who gets stressed over debugging easily). It also seems like it has decent libraries from what I’ve seen so far–I’ll have to examine that more when it comes up (my current project being a roguelike, I only need to print colored ASCII characters). But, it also doesn’t seem fundamentally different from C++, etc. So if you’re into the whole imperative, optionally object-oriented paradigm I recommend it, but I probably won’t be sticking with it for my own use.

The Blue Programming Language

September 29th, 2008

Recently I’ve been searching for a new programming language, becoming discontent with the prospects of Scheme. That’s not to say I don’t like Scheme–just that no one I know is willing to use or read anything I write in it. So, I’m currently looking at a few langauges, and along the way I stopped by a little scripting language Eric Lechak wrote called Blue. It’s got a core object oriented system I like alright, although I feel it has a few too many things left over from C. It doesn’t feel elegant to me (coming most recently from Scheme, what would?), but it executes quickly.

However, this object system I was talking about is pretty neat, because you can arbitrarily give any object an attribute, like a color (string) or a diameter (floating point). Methods are just function attributes. I got into a discussion (read: polite row) about types with Mr. Lechak, and found out that if we add something he names prototyping, we have the object-oriented system of my dreams. Prototyping allows (in C++ terms) every object to act as the “prototype” for a new class.

Now, it makes some things awkward, but since I don’t use too much object-oriented design (no multiple inheritance, for instance) it’s good by me. Mr. Lechak tells me it will slow down execution speed (particularly for his main concern, multiple processors), which I will have to take his word for, knowing nothing about compiler design. Being a firm believer in ease-of-programming over speed of execution, I care not a whit, and continue to be enchanted by the simplicity of prototyping.

Be sure to tune in next week, when I hate prototyping and demonstrate my new favorite language, <foo>.