Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Yakk
Poster with most posts but no title.
Posts: 11115
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Jul 16, 2014 3:38 pm UTC

FFT involves splitting your data into even and odd components, performing a FFT on them, then merging them together to get a FFT of the entire data.

Those two buffers are indeed not in-place, but at the end their contribution is blitted back over the input CArray.

In place in action, but not in implementation.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

letterX
Posts: 535
Joined: Fri Feb 22, 2008 4:00 am UTC
Location: Ithaca, NY

Re: Coding: Fleeting Thoughts

Postby letterX » Wed Jul 16, 2014 6:28 pm UTC

Ahh, got it. So, not in-place like an in-place sort. The extra allocated memory ends up being 2x the amount of memory you started with anyways, which ends up being not bad.

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Wed Jul 16, 2014 9:39 pm UTC

Not necessarily directed at Fancy, but next time somebody seems to have a very hard time taking up programming: Logo (scroll down) may be the way to go. That page has free software, free books and free tutorials. Logo in general is the programming language for learning to program.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Thu Jul 17, 2014 4:35 am UTC

Python has a Logo module in the standard library, if I'm not mistaken.
He/Him/His/Alex
God damn these electric sex pants!

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: Coding: Fleeting Thoughts

Postby Fancy » Thu Jul 17, 2014 4:45 am UTC

I've just entirely given up, I'm much too stupid for coding.
With many little strokes a large tree is felled.
-Japanese Proverb

User avatar
raudorn
Posts: 370
Joined: Mon Jun 13, 2011 11:59 am UTC

Re: Coding: Fleeting Thoughts

Postby raudorn » Thu Jul 17, 2014 3:51 pm UTC

After seeing this talk I decided to build (for fun) a VM for a yet to be specified esoteric programming language. I started with the easy stack operations:

Code: Select all

case IADD:
    stack[sPointer-1] += stack[sPointer]
    sPointer--


and then went on to more complicated things:

Code: Select all

case STORE:
    cPointer++
    mem[code[cPointer]] = stack[sPointer]
    sPointer--
case MPRINT:
    str := make([]rune, code[cPointer+2])
    for i := 0; i < code[cPointer+2]; i++ {
        str[i] = rune(mem[code[cPointer+1]+i])
    }
    fmt.Print(string(str))
    cPointer += 2

... I might be doing memory wrong. I might also misremember the talk. But hey, "it works, it ships", right? I suppose the real fun begins when I try to implement functions and branches.

Triple Log
Posts: 33
Joined: Thu Jul 17, 2014 5:32 pm UTC

Re: Coding: Fleeting Thoughts

Postby Triple Log » Thu Jul 17, 2014 5:39 pm UTC

I feel like I lose any ability to code almost instantly. Like, even taking a short one week break, the syntax and maybe some standard features of languages just become lost on me and I'll spend forever just wondering if something like what I am trying to do is already included/

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Thu Jul 17, 2014 5:43 pm UTC

What language is that?
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6568
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Thu Jul 17, 2014 5:49 pm UTC

Looks like Go.
Summum ius, summa iniuria.

User avatar
raudorn
Posts: 370
Joined: Mon Jun 13, 2011 11:59 am UTC

Re: Coding: Fleeting Thoughts

Postby raudorn » Thu Jul 17, 2014 5:50 pm UTC

Jplus wrote:What language is that?

Go/Golang (the latter is the better search term for obvious reasons)

It makes the code above look a bit strange because newlines replace semicolons as terminating character, cases don't require breaks and there is no pre-increment. The rune type and make function are also a special brand of Go.

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6568
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Thu Jul 17, 2014 6:42 pm UTC

raudorn wrote:
Jplus wrote:What language is that?

Go/Golang (the latter is the better search term for obvious reasons)


Well, when they make version 2.0 of the language, you can simply call it Go2.
Summum ius, summa iniuria.

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Thu Jul 17, 2014 7:34 pm UTC

FT : if you don't understand how your code works, it probably doesn't.

Is that already a programming adage? Because it should be.
He/Him/His/Alex
God damn these electric sex pants!

heatsink
Posts: 86
Joined: Fri Jun 30, 2006 8:58 am UTC

Re: Coding: Fleeting Thoughts

Postby heatsink » Thu Jul 17, 2014 11:27 pm UTC

ahammel wrote:FT : if you don't understand how your code works, it probably doesn't. —Is that already a programming adage? Because it should be.

It's a well-known idea, though I don't know if anyone has aphorismized it. Here's how I would put it:

If you don't understand your code, it can only work by accident.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Fri Jul 18, 2014 12:40 am UTC

... why is the second parameter to strtoul(const char*, char**, int) a char** instead of const char**?

heatsink
Posts: 86
Joined: Fri Jun 30, 2006 8:58 am UTC

Re: Coding: Fleeting Thoughts

Postby heatsink » Fri Jul 18, 2014 1:26 am UTC

EvanED wrote:... why is the second parameter to strtoul(const char*, char**, int) a char** instead of const char**?

The only sensible interpretation I can think of is that the caller should have a non-const pointer to an array. strtoul takes a const pointer since it does not modify the array. It returns a non-const pointer since the caller can modify the array. This solution would require no casting in the caller.

It was the eighties, they didn't know any better.

User avatar
ucim
Posts: 6819
Joined: Fri Sep 28, 2012 3:23 pm UTC
Location: The One True Thread

Re: Coding: Fleeting Thoughts

Postby ucim » Fri Jul 18, 2014 4:26 pm UTC

heatsink wrote:If you don't understand your code, it can only work by accident.
What if you just don't understand your code anymore? Brain-rot doesn't travel back in time.

Another adage I found somewhere - you can write cleverer code than you can debug.

So true.

Jose
Order of the Sillies, Honoris Causam - bestowed by charlie_grumbles on NP 859 * OTTscar winner: Wordsmith - bestowed by yappobiscuts and the OTT on NP 1832 * Ecclesiastical Calendar of the Order of the Holy Contradiction * Heartfelt thanks from addams and from me - you really made a difference.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Fri Jul 18, 2014 5:23 pm UTC

ucim wrote:Another adage I found somewhere - you can write cleverer code than you can debug.
I believe the "original" form of that is due to Kernighan: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Fri Jul 18, 2014 6:14 pm UTC

Jplus wrote:Not necessarily directed at Fancy, but next time somebody seems to have a very hard time taking up programming: Logo (scroll down) may be the way to go. That page has free software, free books and free tutorials. Logo in general is the programming language for learning to program.

I actually used that version of Logo to teach programming to elementary school students for a few weeks. It didn't work so well because that Logo interpreter is quite buggy. I would suggest learning Scheme instead, although it wouldn't work nearly as well for teaching small children.

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6568
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Fri Jul 18, 2014 6:35 pm UTC

New idea for a programming language: Roulette

You have 37 commands, and all statements contain a number 0-36 followed by an identifier or literal. Using a deterministic random number generator (which is not defined by the specs, but is instead compiler dependent) it takes into account the program name, environnent variables, the path, and all previous commands to randomly map 0-36 to each of the commands. This way, your program works only by chance.
Summum ius, summa iniuria.

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Fri Jul 18, 2014 8:47 pm UTC

raudorn wrote:... I might be doing memory wrong. I might also misremember the talk. But hey, "it works, it ships", right? I suppose the real fun begins when I try to implement functions and branches.

This seems like an overly complicated way of doing things. I wrote an interpreter for a simple Javascript-like language for a project once, and I just directly interpreted the abstract syntax tree. Yeah, when you're writing a compiler, you often compile into an intermediate language that can be interpreted rather than compiled to machine code, but why have an intermediate language if you're going to just write an interpreter?

As an example, this is how for loops were implemented in my interpreter:

Code: Select all

function For(init, cond, incr, body) {
    this.init = init; this.cond = cond; this.incr = incr; this.body = body;
}
For.prototype.eval = function(env) {
    this.init.eval(env);
    while (this.cond.eval(env)) {
        this.body.eval(env);
        this.incr.eval(env);
    }
}


A for loop was represented as a For object (which is a node in the abstract syntax tree) with the initialization, condition, increment, and body, and those parts of the for loop were evaluated in the proper sequence.

User avatar
raudorn
Posts: 370
Joined: Mon Jun 13, 2011 11:59 am UTC

Re: Coding: Fleeting Thoughts

Postby raudorn » Fri Jul 18, 2014 9:33 pm UTC

schapel wrote:This seems like an overly complicated way of doing things.

Oh, it definitely is. The mentioned language is really more of an afterthought and I haven't started with it yet. It's really more not to let that perfectly wrong VM go to waste.

schapel wrote:I wrote an interpreter for a simple Javascript-like language for a project once, and I just directly interpreted the abstract syntax tree. Yeah, when you're writing a compiler, you often compile into an intermediate language that can be interpreted rather than compiled to machine code, but why have an intermediate language if you're going to just write an interpreter?

Parsing a language as tree and then evaluating the code-tree is the other often used method to implement a language, so that would've been an option too. Oh and I'll in fact write a compiler, not an interpreter. It just happens that the compiler outputs bytecode instead of machine code, which then runs on a program emulating some weird interpretation of how a CPU actually works. I just keep working on the project until I'm bored, so I don't mind if it performs 500% slower than C. At least I can now write my fizzbuzz for interviews in bytecode, that has to count for something. :lol:

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Fri Jul 18, 2014 10:21 pm UTC

raudorn wrote:I don't mind if it performs 500% slower than C.

That would be kind of fast.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

troyp
Posts: 557
Joined: Thu May 22, 2008 9:20 pm UTC
Location: Lismore, NSW

Re: Coding: Fleeting Thoughts

Postby troyp » Sat Jul 19, 2014 4:08 am UTC

schapel wrote:I actually used that version of Logo to teach programming to elementary school students for a few weeks. It didn't work so well because that Logo interpreter is quite buggy. I would suggest learning Scheme instead, although it wouldn't work nearly as well for teaching small children.

In my opinion, Scheme is the easiest language to learn in the world*, as well as the most beautiful. Of course, not everyone agrees with that. Still, I'd recommend Racket as a first or second language. The big advantage is that many of the best programming texts available use Scheme (including SICP). I doubt you'd even find a book that teaches programming well using C.
* until you start using continuations for flow control, anyway.

Jplus wrote:
raudorn wrote:I don't mind if it performs 500% slower than C.

That would be kind of fast.

It certainly would! It would be running programs backwards at 4 times the speed of C...

edit (FP):

Does time dilate as a language approaches the speed of C?

schapel
Posts: 244
Joined: Fri Jun 13, 2014 1:33 am UTC

Re: Coding: Fleeting Thoughts

Postby schapel » Sat Jul 19, 2014 2:40 pm UTC

raudorn wrote:Parsing a language as tree and then evaluating the code-tree is the other often used method to implement a language, so that would've been an option too. Oh and I'll in fact write a compiler, not an interpreter. It just happens that the compiler outputs bytecode instead of machine code, which then runs on a program emulating some weird interpretation of how a CPU actually works. I just keep working on the project until I'm bored, so I don't mind if it performs 500% slower than C. At least I can now write my fizzbuzz for interviews in bytecode, that has to count for something. :lol:

Ok, sounds like it's for learning purposes. I did a similar thing when I was preparing for an advanced compilers class. I wrote an intermediate language and a compiler, and it occurred to me that if I were doing this for real, it would make sense to write an interpreter for the intermediate language and make sure the front end of the compiler (source code to intermediate language) was working perfectly before I wrote the back end (intermediate language to machine code).

I like the way Terence wrote his interpreter -- it was much simpler than mine, which used a new class for each different instruction. Once you have the intermediate code, it isn't much harder to just emit assembly language for each instruction. Terence actually suggested emitting C code, with a function call for each instruction.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7357
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sat Jul 19, 2014 8:18 pm UTC

I want to create a node object in Python that essentially works as a tree graph (each node has one parent and an arbitrary number of children), but with ordered children (so each node's children is a list, not a set). It needs to allow for depth first searching (from any particular node down), following the ordered list of children.

I keep going back and forth on whether or not I should separate the Graph object from the Node, though -- I originally did because I imagined there was some functionality that differentiates a graph from the nodes that it contains, but as I learn more and more, I start to see that division as less and less relevant. Are there any compelling structural reasons to separate (class-wise) a tree node from the tree graph that contains it?

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Sat Jul 19, 2014 9:02 pm UTC

The only reason that I know of, is that you might want to allow the tree as a whole to be empty, while you might want to maintain as an invariant for the nodes that they always contain a value. In that case, you will need to have a way to have a tree with 0 nodes, so the tree will have to be some different kind of object. You can "cheat" though, by allowing the root node to have "None" as a value (in statically typed languages that would be kind of ugly, but I think it doesn't really matter in Python).
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

troyp
Posts: 557
Joined: Thu May 22, 2008 9:20 pm UTC
Location: Lismore, NSW

Re: Coding: Fleeting Thoughts

Postby troyp » Sat Jul 19, 2014 11:09 pm UTC

The simplest way would probably be to have Node and EmptyGraph as subclasses of Graph. Unless you're using the graph for a very simple, well-delineated purpose which is known in advance, I think it's better to have a "proper" empty graph type. If you try to avoid it, you just end up complicating things (and then add it back later).

Of course, if you're using Python 3.3+, you could always check out this.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7357
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sun Jul 20, 2014 1:11 am UTC

Regrettably, I'm using Python 3.2 (because that's all pygame's been tested up to).

What would be the distinction between a Graph and Node? Would Graph contain the tree structure of all the nodes (and if so, would it be unreasonable to also store that information via pointers in all the various nodes directly)?

I'm curious about the Algebraic Data Types library despite not having the right version of Python to import it; I'm going to try to understand what it's doing anyway, because in general I don't understand a lot of Python's metaprogramming angle.

moiraemachy
Posts: 190
Joined: Wed Jan 04, 2012 9:47 pm UTC

Re: Coding: Fleeting Thoughts

Postby moiraemachy » Sun Jul 20, 2014 1:42 am UTC

So, this is kinda inspired by Fancy's posts, (though not directed to him). It's also kind of a rant, and it's longer than I expected.

The best programming language for beginners is RPG maker. Lacking this, the warcraft world editor will do. Excel macros are okay, I guess. I think all "real" programming languages are horrible for an introductory course, and I firmly believe that people who say they "started programming" with C or Python or Java or Scheme or whatever, and did not hate it, are just wrong. If you didn't suffer, odds are you had some prior experience that involved or is analogous to programming, and that taught you the gist of it.

I still remember figuring stuff out in RPG maker. RPG maker lets you make a Final Fantasy style RPG. You could customize the combat system, character progression, attack animations and so on, but I will only talk about the editing the map. The map, that thing in which the player character walks around with arrow keys and presses A to interact with stuff.

You make the map paint-brush style: pick a tile type, then click a square in the grid to place that tile there. There were two layers: terrain layer (grass, water, lava, wall) and "object" layer, in which you could put fences, chests, trees, etc. The only non-aesthetic property that these tiles have is whether the player could walk through it or not.

However, by double clicking a tile in the "object" layer, a big special dialog box would open, allowing you to place a special tile. You could pick sprites (characters, with animations) as well as the regular objects (rocks, chests) there. It also allowed you to select stuff such as whether the player can walk through it, if it is animated, if it should walk around at random... and there was something about flags and events.

So, the event thing involved a drop-down list to choose a "trigger" (walking on the square, facing it and pressing A, or None), and an empty list. Below the list, you could click "add action", "remove action", "move action up" and "move action down". By clicking "add action", a prompt would give you several options such as "DIALOG BOX", "ADD ITEM TO INVENTORY", "MOVE PLAYER" or "TELEPORT PLAYER". Anyway, after you selected, say, "TELEPORT PLAYER", a new action specific dialog box would appear, asking for example "to where do you want to teleport the player?".

This allowed me to make doors (double click tile, select door sprite, select the trigger to be "when players walks on it", add action "TELEPORT PLAYER: MAP<inside_inn>, TILE<20,2>"), a chest that contained infinite health potions, and NPCs that always say the same thing. One important thing: if you pressed F10 or whatever, RPG maker would start the game with your character at a selected location so you could test stuff out.

Obviously, you can't make a RPG with NPCs that always say the same thing and chests that give you infinite items, so I checked some sample games to see how it was done. First, I noticed they used one action a lot: "IF-THEN-ELSE". I had ignored it at first because it seemed to do nothing (English is not my native language). When you added a IF-THEN-ELSE, it prompted you to select a "condition", and after you selected it added 3 items to the action list: "IF (condition) THEN", "ELSE" and "END". Your action list would end up looking like this:

Code: Select all

IF (INVENTORY HAS: <SACRED ORB>) THEN:
ELSE:
END
DIALOG BOX:<YOU FOUND MY ORB!>
To make the code above work as intended, you would need to select the dialog box action and move it up by two positions. Also,if you deleted one of the parts of the conditional, everything vanished. The conditions, as everything else, were selected from a predefined list ("is item on inventory" or "is flag enabled"). For logic operations, you just selected the option "C1 and C2" and a new dialog box would appear, asking you to specify C1 and C2. This could be nested, naturally.

The second thing I discovered when looking at chests in the sample games. Apparently, you could create an alternate object in the same tile. The first one would be he default, and to the other you could attach some flag. If that flag was enabled, that would be the object shown, not the default one. So here's how you make a working chest: double click the square you want to put the chest on, you select the closed chest for the sprite, you add the actions "DIALOG BOX: <There is a potion in the chest.>", "ADD TO INVENTORY <1> <HEALTH POTION>", "ENABLE: <chest_1_is_open>". Then you add an alternate tile, select the opened chest sprite, select as the "enabler flag" chest_1_is_open (from a drop-down menu), and add the action "DIALOG BOX:<It is empty...>".

Then I noticed I could enable and disable flags and make stuff go back to where it was before. Then I noticed that I could use this to make complex fetch quests, enabling flags only if the player had a certain item. There was an action that activated the actions in another tile ("so the action list in tiles with "None" as trigger are not useless after all!"). After fiddling around a bit, I basically concluded: "yeah, I can script pretty much anything with flags and IFs".

So, at 12 years old, I fully grokked Turing-completeness. But if you asked me if I was programming, I would have said no. In my mind, programming would have been to make the screen flash, or reverse the arrow keys, or open a new window, or delete files. I couldn't do that because these were not in the toolbox of actions that RPG maker gave me. But using flags and ifs, I could script everything I could think of, as long as it only involved stuff such as items being added to the inventory, messing with stats, or moving sprites around.

Only years later would I understand that programming is just that. Except you use the "actions" that the compiler, windows and intel give you.

The experience of messing around with RPG maker was wonderful, and very instructive. I had a system, I understood its rules very well, and I played with it to make new stuff. You can't get that much joy learning in a "proper" programming language.

From that experience, and from watching people suffer as they try to learn how to code, I concluded that every introductory course I have seen sucks. For two main reasons:
- Shitty input and output: C code that beginners write makes letters appear on a terminal. In RPG maker, begginers make A FETCH QUEST IN YOUR OWN VIDEO GAME. There was a time when a program that made letters appear on a terminal in response to what you typed was something interesting. That time is long gone. Now, if you are going to use input from keyboard and output to terminal (booooring), the very least you should do is not also make it a pain to use. First class strings with sane IO functions are the very minimum. Fuck printf.

You want proof of that? Look at logo. It's not significantly different from, say, scheme or lisp. Why is it relatively successful in introductory courses? The goddamn turtle.

- Unclear rules and boundaries: programming is about getting things done with your Turing-complete set of primitives. Valid code can be parsed into a sequence of these primitives. However, according to experts, some people seem to have a really hard time understanding formal languages. I disagree with this view: I believe the problem is not to working within a formal languages, it's seeing the formal language behind the mnemonics and leaky abstractions.

Take C, for example. Some people get that "a = a + 1" involves the add primitive, followed by the assignment primitive. Others might see a primitive in each line, so in their very wrong, but absolutely reasonable mental model, one primitive would be "variable = variable + literal". When they are told that the line "variable + literal = variable" does not work, they don't consider that their mental model might be wrong: it's just another rule. Some expressions are valid, some are not.

The result is that these people end up treating things as "order of operations" not as a specification for how the compiler parses things, but instead as a mnemonic, a helpful suggestion for what expressions are allowed and how they work. And this is not dumb: this kind of informal, "analogy based" thinking is explicitly encouraged and rewarded IN THE SAME COURSE. The program flow structure "if" behaves similarly to the English word "if", the line "a = 2" will "equate" the variable a to 2...

That's how you get people who understand how a piece of code works, what happens when you change the values, but who can't write anything slightly different. This is because when they are confronted with a new problem, their approach is not "how do I chain things I know how to do to solve this?". They instead think "there is probably a new primitive that solves this problem. How can I deduce it?". And they try to deduce it with lousy math inspired analogies, and the result is illegal sentences.

RPG maker doesn't have this. You click "add action". You select from a list. Parameters come in a dialog box. Done. It's literally impossible to make illegal code. These are your tools, go make a RPG. The formal part is fully exposed, no leaky abstractions. This is hard to do in "proper" programming languages because it involves limiting the use of high-level constructs until they are explained formally.

troyp
Posts: 557
Joined: Thu May 22, 2008 9:20 pm UTC
Location: Lismore, NSW

Re: Coding: Fleeting Thoughts

Postby troyp » Sun Jul 20, 2014 4:52 am UTC

The Great Hippo wrote:What would be the distinction between a Graph and Node? Would Graph contain the tree structure of all the nodes (and if so, would it be unreasonable to also store that information via pointers in all the various nodes directly)?

No, the structure would still be in the nodes. Basically, this would be an OO alternative to an algebraic data type. The point of having a tree node would be:
(Note: I'm switching to using Tree and EmptyTree instead of Graph and EmptyGraph, since we are talking about trees, after all, so it's less confusing)
  • To provide a common type for any tree, whether or not it's empty.
  • To contain any common methods that work on either a node or empty tree.
  • (Optionally) To provide purely virtual (ie. abstract) definitions of any common methods that are implemented differently in Node and EmptyTree classes. The methods in the Tree class would just throw a NotImplementedError (you can use a decorator to define these methods automatically). The Node and EmptyTree classes would override the methods with their respective implementations. Python includes abstract base classes now, so you could use that if like*
  • (Optionally) You could include any functionality that operates on multiple nodes, such as traversals.
* personally, I feel kind of funny using abstract base classes to implement algebraic types, since they're really meant to implement, well, abstract types. ("The other ADT", somewhat ironically.) I can't really see a good reason not to, but it'd probably be better to use a simple ADT metaclass.

I'm curious about the Algebraic Data Types library despite not having the right version of Python to import it; I'm going to try to understand what it's doing anyway, because in general I don't understand a lot of Python's metaprogramming angle.

I haven't looked at it myself, I just remember seeing it because I'd been meaning to do the same thing myself. I'm not up on all the latest Python 3 stuff. There's supposed to be improvements for metaprogramming. Which will certainly be welcome, because despite what some Python people may think, Python sucks at metaprogramming.**

** They particularly annoy me when they go on about decorators. Decorators? Who even counts higher-order functions as metaprogramming? And let's face it: decorators are a nice syntax, but they don't add any capabilities. The only reason they needed them is because they lack proper lambda functions and had to introduce new syntax just to handle one special case of using lambdas (ie. f = hof(lambda ...) for a multiline lambda.)

User avatar
Dinosaur!
Posts: 30
Joined: Fri Dec 14, 2012 8:45 pm UTC
Location: Santa Cruz, CA

Re: Coding: Fleeting Thoughts

Postby Dinosaur! » Sun Jul 20, 2014 5:13 am UTC

@Moiraemachy: Man, I can relate to that. My first two 'programming' experiences probably were playing with the StarCraft map editor (which is very similar to RPG Maker) and using Macro Express (not unlike AutoIt) to cheat in MMORPG's by automating crafting. Both of these experiences were around age 11 for me. I never really made anything cool or good in StarCraft, but I made some really awesome crafting bots.

I had functionality like reading pixel colors at X/Y coords to determine inventory contents or exit the game if I received a private message. Walking to and from the bank to deposit/withdraw crafting junk Utilizing randomizers to cause delays within a random range and mouse-clicks in a rectangular region (don't wanna be too consistent or you'll get caught!). Some sophisticated stuff for a preteen, and I knew it and was proud of it. I was obsessed with making better crafting bots; it started out as a desire to get rich in-game without all the work of crafting myself, but I ended up spending more time improving my script than I did actually running it!

And yeah, if you asked me then if I was programming, I'd certainly say no. I had no clue what programming really even was. It was only later (like, ten years later) in my junior college CS courses that I realized that I'd been programming for years -- what a weird experience that was. So, I guess I agree: it's much easier learning to program in an environment completely removed from ints, []'s, i++'s, strings, methods, loops, hashes, return 0's, O(nlgn) < O(n^2)'s, files containing a million random values, and all the other esoteric crap that you're forced to chew through as a first-year CS student. Because programming is really not about any of that junk, it's about the process of analyzing a problem, abstracting it into pieces, and building that abstraction up into a solution. To that end, I think that the best way to learn to program is to find a problem that you really want to solve, and just dive into it using whatever tools you have.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7357
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sun Jul 20, 2014 6:24 am UTC

troyp: Oh wow, thanks -- that makes a lot of sense, now. Also, reading about abc is teaching me a few things I didn't know -- I've been using informal abstract base classes with methods designed to be overwritten (complete with NotImplemented errors), but a means to create an abstract class that raises an error on instantiation -- and an error when a subclass doesn't override its abstract methods -- is something I didn't even know existed.

Also, reading up on Algebraic Data Types -- it's a little more intimidating than I expected, but would a simple way to describe it be a set of rules governing what sort of types are produced when you perform algebraic operations on types?

Ubik
Posts: 1016
Joined: Thu Oct 18, 2007 3:43 pm UTC

Re: Coding: Fleeting Thoughts

Postby Ubik » Sun Jul 20, 2014 9:04 am UTC

I actually just made a tree structure with ordered child nodes at work last week. It was just all nodes without any encompassing tree object. The methods working on the tree as a whole were static ones in a separate class (it's Java, I guess module-level free functions would be a more pythony solution). Not that what I did is any indication of how things should be done.

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Sun Jul 20, 2014 12:44 pm UTC

So I have a C++ project where I'm using a lot of callbacks. I decided to write a "Callback" class, that is basically just a wrapper for an object pointer + a function pointer. I have a function that takes an object and a function-to-member pointer and returns such a callback.

The code looks like this:

Code: Select all

template<typename Res, typename... Args>
class Callback {
public:
   template<typename Object, Res (Object::*function)(Args...)>
   static Callback<Res, Args...> make(Object *object) {
      [...]
   }
};


I can use it like this:

Code: Select all

struct Bar {
   void foo(int x) { }
};
Bar bar;
auto cb = Callback<void, int>::make<Bar, &Bar::foo>(&bar);


It would be very nice if I could rewrite it in a way that would automatically infer the template arguments, i.e. the perfect syntax would be

Code: Select all

auto cb = makeCallback<&Bar::foo>(&bar);

I guess that is not possible to have this syntax because there is no way to declare makeCallback() to take a template parameter of arbitrary type. What is the best approximation one can achieve? Maybe some one who is better than me at juggling with template specializations knows a good alternative.

Triple Log
Posts: 33
Joined: Thu Jul 17, 2014 5:32 pm UTC

Re: Coding: Fleeting Thoughts

Postby Triple Log » Sun Jul 20, 2014 5:16 pm UTC

My interest in coding is diminishing. So many other things I would also like to know, so little time.
I haven't touched code in 4 days!
How do any of you stay motivated?

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Sun Jul 20, 2014 8:33 pm UTC

The Great Hippo wrote:Also, reading up on Algebraic Data Types -- it's a little more intimidating than I expected, but would a simple way to describe it be a set of rules governing what sort of types are produced when you perform algebraic operations on types?

Yes, that would be a way to describe what algebraic typing is about. In my opinion it isn't something you necessarily need to worry about when implementing a tree datastructure, though.

You might like to know that the English wikipedia has quite nice documentation on general concepts related to datastructures (see bottom of page for boxes with cross-links).

korona wrote:So I have a C++ project where I'm using a lot of callbacks. [...]

I might have misunderstood your problem, and I didn't double-check whether the following code is correct, but I suspect you're looking for something like this:

Code: Select all

template <class Res, class... Args>
class Callback {
public:
    template <class Object>
    static Callback<Res, Args...>
    make (Object * object, std::function<Res(Args...)> func) {
        // ...
    }
};

template <class Object, class Res, class... Args>
Callback<Res, Args...>
makeCallback (Object * object, std::function<Res(Args...)> func) {
    return Callback::make(object, func);
}

auto cb = makeCallback(Bar, &Bar::foo);

In fact, Callback::make seems like the kind of function that should be a constructor, in which case I would expect the following:

Code: Select all

template <class Res, class... Args>
class Callback {
public:
    template <class Object>
    Callback (Object * object, std::function<Res(Args...)> func) {
        // ...
    }
};

template <class Object, class Res, class... Args>
Callback<Res, Args...>
makeCallback (Object * object, std::function<Res(Args...)> func) {
    return Callback(object, func);
}

auto cb = makeCallback(Bar, &Bar::foo);


Triple Log wrote:My interest in coding is diminishing. So many other things I would also like to know, so little time.
I haven't touched code in 4 days!
How do any of you stay motivated?

All the things that can be solved using custom code, the fun of taking up a challenge once in a while, and/or work. (All three of those in my case). "Work" may include "study" for some of us.

You seem like somebody who might like to learn about the red spider project (see my sig).
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Yakk
Poster with most posts but no title.
Posts: 11115
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Sun Jul 20, 2014 9:11 pm UTC

korona wrote:So I have a C++ project where I'm using a lot of callbacks. I decided to write a "Callback" class, that is basically just a wrapper for an object pointer + a function pointer. I have a function that takes an object and a function-to-member pointer and returns such a callback.

The code looks like this:

Code: Select all

template<typename Res, typename... Args>
class Callback {


Step 1: rewrite this to be:

Code: Select all

template<class Sig>
class Callback;

template<class R, class...Args>
class Callback<R(Args...)> {

and you can now name your Callback< void, int > to be Callback< void(int) >, much nicer.

Code: Select all

public:
   template<typename Object, Res (Object::*function)(Args...)>
   static Callback<Res, Args...> make(Object *object) {
      [...]
   }
};

You are missing the state of the Callback. Does it have a pvoid and a way to generate a function with a signature Res( void*, Args... )?

Ie, you are only showing us half the use case for it. Which helps if you want it to be improved. :)
It would be very nice if I could rewrite it in a way that would automatically infer the template arguments, i.e. the perfect syntax would be

Code: Select all

auto cb = makeCallback<&Bar::foo>(&bar);

I guess that is not possible to have this syntax because there is no way to declare makeCallback() to take a template parameter of arbitrary type. What is the best approximation one can achieve? Maybe some one who is better than me at juggling with template specializations knows a good alternative.

Well, you can take the Bar::foo by value instead of by template parameter.

But yes, type deduction only occurs in function call contexts. Makes me wish you could take a constexpr arbitrary struct as a template parameter. ;)
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Sun Jul 20, 2014 9:39 pm UTC

@Jplus The problem is that the pointer-to-member is supplied as a template argument and not a function argument.

@Yakk Here is the full code (with your Res(Args...) suggestion implemented). It is actually very simple.

Code: Select all

template<typename Res, typename... Args>
class Callback<Res(Args...)> {
public:
   template<typename Object, Res (Object::*function)(Args...)>
   static Callback<Res(Args...)> make(Object *object) {
      struct Wrapper {
         static Res run(void *object, Args... args) {
            auto ptr = static_cast<Object *>(object);
            return (ptr->*function)(args...);
         }
      };
      return Callback(object, Wrapper::run);
   }

   Callback(void *object, Res (*function)(void *, Args...))
         : p_object(object), p_function(function) { }

   Res operator() (Args... args) {
      p_function(p_object, args...);
   }
   
private:
   void *p_object;
   Res (*p_function)(void *, Args...);
};


I don't want to take the pointer-to-member as function argument because then I would need to store it in the Callback object and have another indirection.

I don't want to use std::function. std::function is fine in that case but in general it needs heap allocations and more indirections which is what I'm trying to prevent. (I have a lot of closures that can be quite large and I need to manage their allocation manually.)

The make function is not a constructor because you cannot pass explicit template arguments to constructors.

Triple Log
Posts: 33
Joined: Thu Jul 17, 2014 5:32 pm UTC

Re: Coding: Fleeting Thoughts

Postby Triple Log » Sun Jul 20, 2014 9:58 pm UTC

Jplus wrote:bunch of text goes here

I'm still trying to learn. I was doing great learning some C, some Python, and on occasion looking at a little bit of ASM, but it got old.

I like physics, math, and literature too. All things that take a lifetime to master.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1446
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Sun Jul 20, 2014 10:16 pm UTC

Triple Log wrote:I like physics, math, and literature too. All things that take a lifetime to master.

Don't worry, and take your time; you've got a lifetime of it!
Image


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 10 guests