Categories
Programming

Language of the Month: Prolog

New month, new programming language to learn, the 3rd one in this series. So the repertoire so far contains:

Prolog

It is again a very different choice, logic programming. Been playing with it for the last two weeks or so, and it really makes me think differently about programming and programs. Logic and complex thinking was always a favorite past-time of me (e.g. solving puzzles and such), but only now I realized that I do have a lot to practice in this area.

Prolog is also one of the older languages (feels like a “classmate” of Lisp and Fortran) so it was the first language in the series where I could actually go to a library, take out some books to learn it, and that book wasn’t hopelessly out of date (try to do the same thing with Python or Ruby…). Since these books were also written by academics and not necessarily computer scientists, their whole approach is different, in a way more curious, though probably less practical.

In the end, I think what I would like to gain is a tool that I can use to attack problems that are intractable or at least very difficult in other languages.

Start

One of the first thing I found hard to figure out was how to actually run a program. So in a nutshell: even if most of the interaction is within an interpreter-like environment, all the basics have to be prepared in a file and loaded.

E.g. I prepare a file like this (based on Ender’s Game), call it ender.pl:

%% Genealogy of Ender's Game.
% Facts
male(ender).
male(peter).
male('john paul').
female(valentine).
female(theresa).

parent('john paul', ender).
parent('john paul', peter).
parent('john paul', valentine).
parent(theresa, ender).
parent(theresa, peter).
parent(theresa, valentine).

% Predicates
father(X, Y) :-
	male(X),
	parent(X, Y).
mother(X, Y) :-
	female(X),
	parent(X, Y).

sibling(X, Y) :-
	father(F, X), mother(M, X),
	father(F, Y), mother(M, Y),
	X \= Y.
brother(X, Y) :-
	male(X),
	sibling(X, Y).
sister(X, Y) :-
	female(X),
	sibling(X, Y).

Then starting Prolog I can load the file with the [‘ender.pl’]. form, and ask questions like who is Ender’s sister? Who are Theresa’s kids? Who are Peter’s siblings?

?- ['ender.pl'].
% ender.pl compiled 0.00 sec, 144 bytes
true.

?- sister(Sis, ender).
Sis = valentine ;
false.

?- mother(theresa, Kid).
Kid = ender ;
Kid = peter ;
Kid = valentine.

?- sibling(peter, X).
X = ender ;
X = valentine ;
false.

Well, this is laughably simple, and I’m beyond this already, but it’s good for a first illustration.

By the way, it looks like 90% of elementary Prolog examples use family trees (Nordic or Greek gods, literary, real families…)

Now let’s get in there and learn some more stuff…

Links

Tutorials & Info

Books

Compilers

Code

Categories
Programming

Language of the Month: Lua, part 2

I’m a few days behind schedule since Lua was June’s language, but here it comes, some summary of my experience, after setting things up in the first part.

A Trip to the Moon / Le Voyage dans la Lune
Lua is not this painful, indeed, just the opposite

Overview

I really liked this language, and I’m sure I’ll keep learning it. Very useful and lots of interesting concepts. I haven’t seen an embedded language before, and some parts

Most of what I picked up was from Beginning Lua Programming and Programming in LuaLua Missions was another very useful experience: a “fill in the blank” type of source code collection, which drilled my understanding of the Lua concepts. Some sections felt a little short, so maybe later I’ll think whether there are any more questions I can come up with. Very well worth the time!

There are two things that stand out: tables and local environments.

Tables

If I have to refer to my knowledge of Python, then Lua tables are like Python lists and dicts rolled into one and then some. Here’s one such table:

x = {1, 2, 3, y = "something", ["or else"]="what"}

The first three elements are giving an array (and one can loop over them), then the last two are key-value pairs. One tricky thing is that the “y” there is actually a string (the same as [“y”]), just made it more readable with syntactic sugar. Since variables (references to variables) can be keys as well, this can get confusing if one has a variable called “y”… There are quite a few things about tables that are confusing, but actually pretty consistent so my fuses are not blowing that much as they were in the beginning (for example: how the length is looked up, how to iterate through the different values) .

They are very complex animals so some things are quite complex to do, which in turn enables quite complex things to be done. Pretty much any kind of data structure can be built upon them. So all in all, I’m enjoying them with all their quirks. Also, “weak tables” are an interesting concept (where certain table entries can garbage collected).

Scopes

In Python, the name spaces and environments seem to be on the sidelines (at least what I’ve seen so far): people need it and have to us it, but nothing more than that. In Lua this is taken to a whole new level: scopes can be essential parts of the way algorithms are implemented and neat tricks can be played.

I tried to come up with some good example and failed, here’s a “duh” one:

function newCounter ()
    local i = 0
    return function ()   -- anonymous function
        i = i + 1
        return i
    end
end

c1 = newCounter()
print(c1())  -- 1
print(c1())  -- 2

This is a bit like Python’s “yield” type of generator, without anything special.

Also, in Python there are only two kinds of variables (I think): local and global: either just for you or for everyone. Here they have one more: upvalues, where the variable is local to a parent, so children environment can access them but the parent’s parents cannot. They are strange beasts as well, e.g. the code itself cannot really know if a variable is upvalue or global, only that it can access that.

And of course these scopes help embedding to not just be possible but straightforward and powerful. Local environments can be restricted, some things selectively enabled, and all this transparently, so the script running might not even know that it’s being in the Matrix.

The Lua Experience

Good

  • Fast, both start up and running
  • Language itself is quite small, possible to wrap one’s head around quite easily
  • Written in ANSI C, so basically on every architecture where one can run C, one can have Lua as well
  • Quite a few program has Lua interpreter or interface built in, see the list of these at Wikipedia
  • Tables are great and once one mastered them, are really Swiss Army Knives
  • Built in interpreter (though could use a little love like iPython)
  • The “…” syntax for variable number of arguments
  • Astrological naming convention – modules are rocks, the exercises I linked previously are missions, web framework is Kepler

Bad

  • There seem to be a lot of reserved names (e.g. in metatables) that would be pretty much impossible to figure out with a book (and/or an iPython-like helpful environment), though this is a problem probably only when starting out with Lua

Ugly

  • While some complex things can be solved, some simple things can require complex coding (e.g. in case of the tables when using “__index” and “__newindex“) and there are things that are not even possible. Or I just misunderstood some sections of the book.
  • Using a lot of syntactic sugar (especially in the object oriented section), that I feel need some more practice to pick up, as things can be done in multiple ways
  • The tables’ syntactic sugar covered way of handling string keys, convenient when things go well, mighty confusing at even the slightest problem
  • Too few projects using Lua, too few sources of information (this is not the language’s fault, though)

Project

Originally I wanted to do some useful programming in every language I learn during the Language of the Month series. I failed with Scala (lazy), and now failed with Lua too (underestimating the difficulty). I’m using VLC a lot and it has Lua scripting enabled, so I wanted to do a plugin that can be useful for me later as well. This didn’t work out very well, mainly because it feels the VLC Lua interface is not very well documented, one mostly have to find some examples that exist already and use them. I ended up wasting a lot of time and still don’t quite understand how to do certain things I would like for my code, and don’t even know if it’s possible to do or not. Will come back to it later, until that here are a few links that helped me to get started:

  • VLC Lua FAQ – detailed list of available API functions, but almost no context and examples
  • Lua extensions in the VLC git repo – one can pick up something by checking out those examples
  • Example: Streaming Radio Player Extension – someone who have gone further down this road than me and has a working extension. Very educational, especially to see how concise and straightforward it can be, because the VLC Lua API seems to be thought out well.

Again, hopefully pick this up later (I mean it).

Categories
Taiwan

Entrepreneurship Challenge

Since my first (crazy) swing at anything business I consider myself “infected”. It seems like that is only a matter of time I start my own venture, for better or worse. It is just too much fun and to difficult to stay out of it.

Challenge

In line with that attitude, now I notice all kinds of related events, and fortunately some of them are in the neighbourhood. So, last Sunday found me at an entrepreneurship challenge – a business plan competition. It was organized by a local startup, Enspyre. It’s founder is a serial entrepreneur who started at the age of 15. The company itself also runs an internship program to find interesting/creative people, and I have no doubt that the event was aimed inspiring young people to start something new – which in turn would boost their own business. I say, double-clever!

The audience was quite mixed, of the 25-30 participants more than half was Taiwanese, mostly students in their sophomore and senior years. The rest of it were strange foreigners (your’s truly is no exception), from Indian software engineer to Filipino Business majors and American expats. The day was supposed to be learning by doing. First, some current entrepreneurs and VCs present their take on what is a business idea and how a business plan and a pitch comes out of it. Then, in the space of a couple of hours, people would form more-or-less random groups, come up with ideas, refine them, do some numbers of how much capital the idea would need, prepare a pitch, deliver it – and see how it flies with the real VC judges. Most of the people did each and every step of this process for the very first time. Sounds intense? It was and also incredibly stimulating.

Entrepreneurship Challenge
Entrepreneurship Challenge, "Double Dream" pitching

Experience

In the initial “name card exchange” phase I was really slow – or at least slower then the rest of the people. I did want to know a little bit about my potential team mates, so ended up talking more to them than the other (I guess 5 sentences instead of 1). This made me in the end one of the last person to choose a team. That’s not a problem, I like random, usually works out brilliantly.

Out of the 5 members, our team had 4 Taiwanese students (2 business, 1 psychology, 1 medical science) and me. The language posed a little bit of difficulty, but I’d say we worked around it pretty well (I came a long way in terms of patience since I started learning Chinese as well). It was pretty amazing to work with them, especially because we all didn’t know each other, and that I could resist pushing my own things.

Some lessons learned:

  • The original business ideas were pretty bad. Many of the better ones were maybe a bit too conventional. On the other hand, when we revisited them, each and every was brainstormed into something I could feel excited about and would be totally happy to start working on. It was absolutely awesome to hear and discuss their ideas, to live through the process. Later talking to some other groups, their ideas just grew but none of them changed substantially upon review. Sign that we had a naturally agile team?
  • The language barrier is pretty big at the moment. Once one gets beyond that, by either having more patience, communicating even a tiny bit in their native language, or letting them discuss things between themselves for a whole, creativity really shines. There’s a lot of potential in this country. (Not that I didn’t know that earlier:)
  • Feedback from VCs, even – and maybe especially – before pitching is invaluable. That is, if I can say my question clearly and concisely enough. And that gave me a duh moment: of course they want everyone to succeed. If your idea/pitch is boring, they are going to waste the time. If there are few creative people then they will have fewer investment opportunities. So it is their very on selfish interest to do everything for you to succeed. Don’t abuse it (i.e. make it more trouble for them to help then the potential reward) and you have the best teachers.
  • It’s good to take the back seat sometimes. I didn’t push that our group would develop one idea originating from me, but one that more people in the team liked. I had advantage in the language front so pitching wouldn’t have thought me much, I insisted that the girl (Ping) who came up with our original idea would do the pitch – regardless of her English. She protested first but in the end I’m sure she liked it. This way she had some awesome experience and I could also see (ie. introspect) how do I listen e.g. to a pitch – even our own. I’m sad to say, that I’m a terrible listener. Got to fix that, and glad I had a chance to realize it.
  • As we were told multiple times during the day, the team is more important than the idea. After working together for a few hours I can certainly see how that comes into play very-very quickly. The business ideas I had these days lack any kind of consideration who would I do them together with – really should think about who else is in my social circle who I should consider because no matter how idealistic I am, I won’t make it completely on my own.

Guess these are just part of what I have realized, the rest of it will probably pop up every now and again in the coming weeks and months.

And now for the punchline: out of the 6 teams we took home the first prize. We came up with an idea that could impress other people who are doing this for a long time (and one of whom were telling us how the salesgirls pamper you much better when buying an Armani suit than at any other boutique – a lifestyle clearly out of my league). Their feedback was that out of the 6 pitches, ours was the one that could be done realistically, on a sane budget, with sane assumptions and might just work! It is an interesting feeling. I want to keep this and continue growing on it. Already started: my part of the bounty for winning went for recovering the entrance fee and “investing” in more resources for my journey (“Technology Ventures”).

Categories
Programming

Language of the Month: Lua

New month, new language. So far in this series:

I think I do want to amend the original rules set up for this Language of the Month series. At first I though I can write a new project in any language I learn. That is probably too ambitious. So new rules: every month write a new project in the given language OR contribute to an open-source project in that language. This should take away most of the stress and add some social aspect as well. :)

Lua

I’m intrigued by this language because of it’s niche: scripting language within other software. How one sets out to do something like this? What are the requirements for the language, in terms of design, syntax and so on?

Lua programming language logo
See, the moon!

First impressions

So far I was trying out some code snippets and example scripts. First thing to notice was that Lua is pretty darn quick to start. And pretty quick to run as well, though I haven’t used it for very heavy computation yet. E.g. the “get_all_factors” code at the Lua Crash Course (using a larger example number, 1029384756) is timed at ~7ms, wheres the same version on Python (the language that I probably know best and compare other languages to) runs ~10x slower. The snappiness of a scripting language is a surprisingly happy feeling. :)

Tables look very interesting, how the same thing can implement several data structures at once (it’s like Python’s dict, list and kinda-struct at the same time).

Quite intriguing that the Lua Virtual Machine is stack based, probably that’s the reason the language is so embeddable. A while back I was looking for a language with small resource (especially memory) requirements. I had a few suggestions (Dalvik, Forth) that were interesting, but maybe Lua is the one?

The “local” keyword (and the reasons for having it) seems to be a possible source of many harder to debug scenarios. Got to keep this in mind, again not being in Pythonland anymore.

Interesting how the “function” can be defined inline, so looks like there’s essentially no need for a special “lambda” keyword, at the expense of tying a few characters more…

The interpreter is quite well done (with it’s intelligent indentation probably even better then ipython, though would love to see more colours ^^)

As an exercise, here’s a version of FizzBuzz:

function fizzbuzz(num)
   --[[--
   The usual FizzBuzz from Jeff Atwood
   Doing it a bit roundabout to try some Lua language features
   --]]--
   local answer = ""

   if (num % 5) == 0 then
      answer = "Fizz"
   end
   if (num % 3) == 0 then
      answer = answer .. "Buzz"
   end

   if answer ~= "" then
      print(answer)
   else
      print(num)
   end
end

-- Run the thing
for num=1,100,1 do
   fizzbuzz(num)
end

Links

This section will be updated gradually as I find more information.

(Edit: added the second part of this experiment.)

Install

Tutorials

Books

Articles and info

Source of code

Projects using Lua

Categories
Programming

Language of the Month: Scala, part 3

This is a post I should have written yesterday, actually, since it is already June, ready for the next “Language of the Month“. Still, let’s finish off this May Edition.

Taking score

First, I should have spent more time on practicing Scala, as I haven’t actually finished anything in the end. It is probably an excuse, but after using Python for such a long time, getting used to a compiled language with its own weird path-, naming- and import conventions, was just a little bit too much. Mostly I was reading the Pragmatic Bookshelf: Programming Scala, practicing the examples within. That book uses Scala 2.7.x and the current version is 2.9.0.1, so there are a few things that work differently and I ended up having strange error messages with little to no clue how to fix them (mostly imports, and some method signatures must have changed as well). So it was a limited but exciting success.

Scala screenshot
Using them example code

All in all, I liked the language even if I don’t have a clear usage case for it in my mind (just yet). Some bullet-points of my experience:

Good

  • Different way of thinking about “batch” operations (i.e. foldLeft)
  • Once I figure out the Actors that well that I can write related code without referring to the tutorials, that’s going to be a very powerful tool
  • Pattern matching, pattern matching everything. This is one thing that blown my mind in the little Haskell I checked so far, and missing from Python a lot.
  • Flexibility with class definitions, they can handle so many different situations in a very logical and powerful way

Bad

  • Length of compilation and program start. Will have to get used to it, though I read some hints that this can be improved.

Ugly

  • Pretty frequent need of using things directly from Java, so one is never quite independent
  • Special methods that have reserved name for certain functionality (act, apply, …) that are non-obvious, and not easily distinguished from the arbitrarily defined methods.

Future

Definitely will come back to it and learn it in more detail. It looks like a fine language to do parts of larger projects in. In the meantime I will update the link collection in the previous post with new links that I find. I certainly notice more and more Scala posts on Hacker News these days.