Coding: Fleeting Thoughts

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

Moderators: phlip, Moderators General, Prelates

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sat Sep 13, 2008 11:16 am UTC

Today, in my car, I realized that characters in python are nothing more than lists containing themselves. See, a python string is a list of characters, but python characters are strings of length one, hence a list containing one character; itself.

Not really a big realization, but a fleeting thought nonetheless.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
sparkyb
Posts: 1091
Joined: Thu Sep 06, 2007 7:30 pm UTC
Location: Camberville proper!
Contact:

Re: Coding: Fleeting Thoughts

Postby sparkyb » Sat Sep 13, 2008 2:57 pm UTC

Berengal wrote:Today, in my car, I realized that characters in python are nothing more than lists containing themselves. See, a python string is a list of characters, but python characters are strings of length one, hence a list containing one character; itself.


Your point being that you can do this?

Code: Select all

s = 'x'
if (s==s[0][0][0][0][0][0][0][0][0][0][0]):
    print "Yep"


That is a little profound.

vortmax
Posts: 13
Joined: Thu Aug 28, 2008 4:28 pm UTC

Re: Coding: Fleeting Thoughts

Postby vortmax » Mon Sep 15, 2008 1:18 am UTC

i keep having these strange fleeting thoughts, usually as I'm falling asleep.

Like, is DNA biological machine code or is it assembly? Would that make cells objects and mitochondria methods?

Strangely enough I started having these thoughts/dreams after first attempting to learn perl.

Agent_Irons
Posts: 213
Joined: Wed Sep 10, 2008 3:54 am UTC

Re: Coding: Fleeting Thoughts

Postby Agent_Irons » Mon Sep 15, 2008 2:02 am UTC

My fleeting thought is that (nearly) every project euler problem has three stages.

Stage 1) Wonder how to solve the problem. Write some spaghetti code, throw it out.
Stage 2) Get an elegant way to solve it. Spend some time trying to figure out why your compiler is throwing a fit.
Stage 3) Have code that compiles. Now try and work out why it won't give you the right answer.

I'm on Stage 3) With several problems at once.

User avatar
madprocess
Posts: 65
Joined: Mon Sep 18, 2006 9:35 pm UTC
Contact:

Re: Coding: Fleeting Thoughts

Postby madprocess » Mon Sep 15, 2008 4:41 am UTC

Agent_Irons wrote:My fleeting thought is that (nearly) every project euler problem has three stages.

Stage 1) Wonder how to solve the problem. Write some spaghetti code, throw it out.
Stage 2) Get an elegant way to solve it. Spend some time trying to figure out why your compiler is throwing a fit.
Stage 3) Have code that compiles. Now try and work out why it won't give you the right answer.

I'm on Stage 3) With several problems at once.


I'd propose that there's a few more stages.
Stage 1b) Research how to do it/"Steal" someone else's code.
Stage 4) Wonder endlessly if there was a more elegant solution would have been, rather than brute forcing

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Mon Sep 15, 2008 10:50 am UTC

Berengal wrote:I cannot for the life of me find all the proper divisors of a number given it's prime factorization.

Update on this: I knew it had to do with power sets and all that, but I still couldn't figure it out. I had all the knowledge I required, and yet the solution escaped me. Today, after not thinking about it for a few days, I sat down and wrote the functions in less than five minutes.

Code: Select all

powerSet :: [a] -> [[a]]
powerSet [] = [[]]
powerSet (x:xs) = map (\s -> x:s) subPowerSet ++ subPowerSet
                where subPowerSet = powerSet xs

properDivisors :: Integer -> [Integer]
properDivisors n = sort . map product . nub . powerSet . factorize $ n


Now to complete those project euler problems I got stumped on.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Mon Sep 15, 2008 10:38 pm UTC

Not entirely coding but...
My old laptop got nailed in the screen by something and I hooked it up to an old CRT and fakeUSB keyboard. It ran Ubuntu wonderfully until it crapped out during a file server makeover. I reinstalled XP so I could do it the way I knew how and it wouldn't even see the ethernet bus. I now have an XP laptop that can't get to the internetany networks, period. GAAAH!

Edit: I just noticed that Microsoft Word tries to connect to a printer when you close it. Stupid code much?
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Tue Sep 16, 2008 5:32 pm UTC

I like literate programming.
An assignment I just handed in was mostly theory, but had a small programming part as well. Since Java is the only language we're guaranteed to know at this point, and since java is pretty ugly, it was pretty specific about how it wanted it's java files to be handed in. I opted instead to write the programming part in Haskell, and hand in the entire assignment (60% long answers, 35% simple answers, 5% code) as a single .lhs file. Reads as a regular text file, compiles as a regular source file.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Sep 18, 2008 3:31 pm UTC

Thought of the day: I want to round up and shoot every single typedef'd structure pointer.

Background: I've been helping this guy I know out with an assignment to a course in algorithms and data structures. He was given a C header with function and structure definitions. All good and well, only the header is riddled with (frequently used) typedefs of the variety

Code: Select all

typedef struct foo* foo;


Sure, it looks pretty and Java-like. But what the hell? It completely screws up the code. Instead of something clean and understandable like this:

Code: Select all

foo* bar = malloc(sizeof(foo));

You have to do this everywhere:

Code: Select all

foo bar = malloc(sizeof(struct foo));


That is a segmentation fault just waiting to happen. So yeah. Hiding the pointerness of a widely used type. It's just... evil. It's horrible. It should be capital offense. C isn't Java. C doesn't have object references. Trying to make it into Java by means of dubious typedefing will cause way more problems than any benefits you could possibly obtain.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: Coding: Fleeting Thoughts

Postby Rysto » Thu Sep 18, 2008 4:35 pm UTC

That's why you do:

Code: Select all

foo bar = malloc(sizeof(*bar));

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Sep 18, 2008 4:57 pm UTC

That is only slightly better. The fundamental problem doesn't go away. The variable declaration is still vague on what the hell the type is. When handling pointers, it is paramount you know exactly what the type is.

This type of programming is symptomatic to a fear of pointers that is all too common; it's rooted in the idea that pointer manipulation is some black monolith best left alone, and the less you see of them, the better. Clearly, these programmers never saw 2001: The Space Odyssey, and are unaware that black monoliths make you smarter.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

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

Re: Coding: Fleeting Thoughts

Postby EvanED » Thu Sep 18, 2008 8:09 pm UTC

I would say that style of programming makes some sense, but only if the type is completely opaque... e.g. you would never write foo bar = malloc(sizeof(*bar)); because you would never malloc it yourself, you would just say foo bar = create_foo();. At this point you don't even need to know that foo is really a pointer to something, and for all you care it isn't.

Of course, it's still questionable, and you still need to know that the object will have reference instead of value semantics, so I would still recommend against it.

User avatar
phlip
Restorer of Worlds
Posts: 7569
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Thu Sep 18, 2008 10:49 pm UTC

Even for an opaque type, it's kinda important to know it's a pointer, and not, say, a struct (which would have different semantics for copying). Having to mess with a pointer to an opaque type still makes things clearer. See also: FILE*.

Incidentally: The Windows headers are full of such definitions... but there's a naming convention there, they all start with P and/or LP (a holdover from Windows 3.1, which still had near and far pointers). They even go so far as to have "typedef void * LPVOID;" and such.
I almost never use them... except in very heavily-Windows-ed code, I'll often use LPSTR/LPCSTR instead of char*/const char* to differentiate a pointer to the top of a string from a pointer to a single char. Other than that one case though, I'd always rather use WHATEVER* than LPWHATEVER.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Fri Sep 19, 2008 5:32 pm UTC

As long as it is just pointers to plain old data being typedef'd, the damage isn't that bad, it's when you start typedefing pointers to structures and unions the havoc and mayhem is unleashed. The P/LP convention alleviates it just slightly, but it is on the other hand pretty meaningless, since you have to indicate that the typedef is a pointer in the name where you could simply have typedef'd the referred type and used a * to indicate pointerness.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Mon Sep 22, 2008 4:38 pm UTC

I found a better project to do in Python: Lazy Evaluation. It takes a function, which must have a parameter for the index of the calculated number, and the list of all elements before it. The first part is the class itself; the second part shows it in action.

Code: Select all

class LazyFunction(object):
    def __init__(self,newfunction):
        self.function=newfunction
        self.evaluated=[]
    def evaluate(self,n):
        if n<len(self.evaluated):
            #already calculated
            print "already found"
            return self.evaluated[n]
        else:
            i=len(self.evaluated)
            while(i<=n):
                #loop through unsolved until we reach goal
                self.evaluated.append(self.function(i,self.evaluated))
                i=i+1
            return self.evaluated[n]

def triangleNum(n,previousterms):
    if(len(previousterms)==0): return 0
    return previousterms[n-1]+n
trianglenumbers=LazyFunction(triangleNum)
for x in range(10): print trianglenumbers.evaluate(x)
for x in range(10): print trianglenumbers.evaluate(x)

As far as I know, this can take any possible sequence.
Edit: Berengal, best post ever, and thanks for the correction.
Last edited by headprogrammingczar on Mon Sep 22, 2008 7:35 pm UTC, edited 1 time in total.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Mon Sep 22, 2008 6:25 pm UTC

That's actually a memoizing function you've made, not a lazy evaluated one, and there's an easier way to make them:

Code: Select all

def triangleNum(n, memoized=[1]):
  l = len(memoized)
  if n < l:
    return memoized[n]
  last = memoized[-1]
  while n>= l:
    next = last+l+1
    l += 1
    memoized.append(next)
  return memoized[-1]

Or even better, in case your function doesn't have to know the preceding incantations:

Code: Select all

def f(x, memoized={}):
  if x in memoized:
    return memoized[x]
  result = 3*x + 5
  memoized[x] = result
  return result

Let's make it a class that takes a function and memoizes calls:

Code: Select all

class MemoizedFunction(object):
  def __init__(self, function):
    self.func = function
    self.memoizedCalls = {}
  def __call__(self, *args, **kwargs):
    kwargtuple = tuple(kwargs.items())
    if (args, kwargtuple) in self.memoizedCalls:
      return self.memoizedCalls[(args,kwargstuple)]
    else:
      result = self.func(*args, **kwargs)
      self.memoizedCalls[(args, kwargtuple)] = result
      return result

Or even better yet, a higher order function, popular in a pattern called the decorator pattern, which has it's own syntax in python:

Code: Select all

def memoized(func):
  memoizedCalls = {}
  def memoizedFunc(*args, **kwargs):
    kwargtuple = tuple(kwargs.items())
    if (args, kwargtuple) in memoizedCalls:
      return memoizedCalls[(args,kwargtuple)]
    else:
      result = func(*args, **kwargs)
      memoizedCalls[(args, kwargtuple)] = result
      return result
  return memoizedFunc

Decorate functions like this:

Code: Select all

@memoized
def f(x):
  return 3*x+5

# The above is equivalent to the following, less clear and less cool statement:
def f(x):
  return 3*x+5
f = memoized(f)


I started research on lazy evaluation in python, but didn't get very far. I've got an idea, but it's going to take me a few hours at least.

Edit: I gave up on the lazy evaluation. My idea'd change the syntax of the language too much. Anyway, just thought I'd say that with memoized functions, recursion gets a bonus vs iterative programming, since every call is memoized. If you're doing lots of factorials, for example, it's better to write the function recursively, since that'll memoize every argument below your highest ever, while producing the result iteratively only memoizes that one call.
As an aside, my naive solution to Project Euler's problem 15 takes ages (didn't care to wait), as expected, but by simply declaring it memoized, it resolves in an instant (8 ms).
Last edited by Berengal on Mon Sep 22, 2008 7:19 pm UTC, edited 1 time in total.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

btilly
Posts: 1877
Joined: Tue Nov 06, 2007 7:08 pm UTC

Re: Coding: Fleeting Thoughts

Postby btilly » Mon Sep 22, 2008 6:55 pm UTC

Berengal wrote:I started research on lazy evaluation in python, but didn't get very far. I've got an idea, but it's going to take me a few hours at least.

You might like Infinite lists in Perl. The techniques described there of using closures to lazily generate infinite data structures should translate very easily into Python.
Some of us exist to find out what can and can't be done.

Others exist to hold the beer.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Mon Sep 22, 2008 7:24 pm UTC

There's already generators, which provide for most of my infinite needs. The problem with lazy evaluation is how to best create a value that isn't reduced to normal form unless it's absolutely required.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Mon Sep 22, 2008 7:36 pm UTC

Wow. I am obviously a Python newb.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Tue Sep 23, 2008 12:26 pm UTC

btilly wrote:
Berengal wrote:I started research on lazy evaluation in python, but didn't get very far. I've got an idea, but it's going to take me a few hours at least.

You might like Infinite lists in Perl. The techniques described there of using closures to lazily generate infinite data structures should translate very easily into Python.

I'm glad I read that article anyway. In addition to being an interesting read about lazy structures (I still think generators are the way to go), it helped me solve problem 204 in Project Euler.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
sparkyb
Posts: 1091
Joined: Thu Sep 06, 2007 7:30 pm UTC
Location: Camberville proper!
Contact:

Re: Coding: Fleeting Thoughts

Postby sparkyb » Wed Sep 24, 2008 6:36 am UTC

Nice work on that memoizing decorator, Berengal. Only problem I see with it is that it differentiates between different ways of setting the same parameters (as a positional argument, as a keyword argument, or via its default argument). I was thinking about writing a thing that would use the function's code object to find out the actual argument names and default values and resolve *args and **kws to a normalized form for use as a key to memoizedCalls. I realize that it would be overkill but I was going to do it just for fun but then I decided not to waste my time. An example of the problem:

Code: Select all

@memoized
def f(x,y=1):
  return 3*x+5*y

# the following are all the same but will be memoized separately
print f(2)
print f(2,1)
print f(2,y=1)


I'm not sure exactly what kind of lazy evaluation you want. I've done it before where I have a function allow its arguments to be values or else functions that return the values so that the value isn't calculated until the function/class needs it.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Wed Sep 24, 2008 10:42 am UTC

Yeah, I know my memoized decorator isn't perfect, and the problem stems from generalizing the arguments. The undecorated function f has signature f(x), but the decorated has signature f(*args, **kwargs), which can confuse code inspectors, and yield confusing errors. There is a way to resolve this using reflection and setting the signature of the returned function, but I'm not too familiar with it. I do however suspect that using the same method to normalize the arguments shouldn't be too hard.

Using functions to make evaluation lazy is basically what you have to do. The problem is doing this in a strict language in a way that doesn't mess things up. Haskell uses thunks, which is basically just a function (a promise that there is a value there, and a way to find that value). You can use functions for the same effect, but you need a way to replace that function with another function that simply returns the result of the previous function. Laziness also has to not evaluate a value unless it's strictly required, and that requires dedication on the part of the function writers, as everything has to be wrapped in the lazy framework. For example, a list of all squares would look something like [x*x | x <- [1..]] in Haskell. When you ask for the fourth square number, it'd evaluate something like:

squares !! 3 = *thunk* -> [*thunk*...] -> [*thunk* , *thunk*...] -> [*thunk*,*thunk*,*thunk*...] -> [*thunk*,*thunk*,*thunk*,*thunk*...] -> [*thunk*,*thunk*,*thunk*,*thunk*, *thunk*...] ->[*thunk*,*thunk*,*thunk*, 16 , *thunk*...]

Where the last thunk in a list is the rest of the list and the previous thunks are elements in the list. Before the first thunk is evaluated, it doesn't even know it's a list (but it's strongly typed, and the type system knows).
Unless you're extremely careful when writing such a list in python, you could easily end up with a strict evaluation somewhere, and that could potentially spell infinite doom (well, generators would make such a list for you, but there are some things they cannot do alone which lazy evaluation can). You'd have to wrap everything in lazy evaluation wrappers, and that'd quickly get tedious.
Not to mention lazy evaluation forces purely functional programs, which means no side-effects. Lazy evaluation in python should restrict itself to lazily evaluated infinite sequences, which generators take care of for the most time.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Sep 25, 2008 6:11 pm UTC

I had the fleeting thought that I suck at writing manuals just now, as I read on the following subsubsubsection of the manual I'm working on:

4.1.2.1 Arbitrary commutative ternary tritwise operator operator <<N>>

3CC has an arbitrary commutative ternary tritwise operator operator, with the following syntax:

a <<N>> b

This specific command will execute the operator with FFUUTT-code N with parameters a and b. See section 6.2.3 for the meaning of FFUUTT codes and arbitrary ternary operators.


This brought me to the realization that it probably would be more helpful to simply paste the sources into the manual.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
kovan
Posts: 169
Joined: Mon May 26, 2008 7:40 pm UTC
Location: Toronto
Contact:

Re: Coding: Fleeting Thoughts

Postby kovan » Thu Sep 25, 2008 8:54 pm UTC

Up until I started looking at C++ again I never really appreciated how creatively lazy pointers allow me to be. Reference variables can never measure up.

User avatar
Xanthir
My HERO!!!
Posts: 5400
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Tue Sep 30, 2008 12:08 am UTC

After doing some Googling for some help on approaching a project Euler problem, I ran across this guy doing the problems in C# with LINQ. I had *heard* of LINQ before, but thought it was something weird having to do with SQL. His use of it intrigued me, though, so I looked up some documenation, which led me to this starting conclusion (I'd heard it before, but this was the first time it was *real* to me):

We Lispers don't have to convert a single person to our way of thought. Given enough time, every language will simply turn *into* Lisp on its own.

Sort of an application of Greenspun's Tenth Rule to language design itself.

(Just to make myself more clear, the "query-like" syntax of LINQ is a kissing cousin of Lisp's Extended LOOP, with a few things thrown in (like "order by") that would be handled in Lisp by wrapping the result of the LOOP in another function (like sort). The explicit syntax is just ordinary functional programming. Add in anonymous types (= typeless lists) and lambda expressions (...) and you have a proper functional language built right in that greatly resembles Lisp.)

I mean, seriously, give me C#3.0 and a reference document translating LINQ functions back into their Lisp equivalents, and I could code C# straight.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Fri Oct 03, 2008 12:08 am UTC

My interpreted browser project was put on hold when a new compulsory assignment was dumped on me. Because of work, I've been missing a couple of lectures, and I have yet to get the book we're using (it's both expensive and hard to obtain even if you've got the money... go figure), so I know jack all about parsing, ASTs and evaling. We're supposed to build an interpreter for a very minimalist language, and we're supposed to do it in SML. I don't know SML yet, so I'm doing it in Haskell instead (I asked, and they said okay, but under doubt). The following touches every element in the entire language:

Code: Select all

letfun f X be
  *(X, X)
in
  let A be 3 in
    +(f(5), A)
  end
end

In short, variables are single-letter capital letters, functions are single-letter lowercase letters and (parsed) integers are a single digit (because for some reason SML can't read an int from a string, or at least the professor doesn't know about it). Whitespace is optional, so the previous is identical to the following:

Code: Select all

letfunfXbe*(X,X)inletAbe3in+(f(5),A)endend

I've yet to start on the parser, but I just finished describing the AST, and writing an interpreter for it. I gotta say, those lets were hard. I spent hours figuring out how to do the let, then read on that there were also letfuns (but they were "optional"). I finally got it, and now I can't go to sleep...
The happiest line Haskell interpreted for me today (hand-made AST):

Code: Select all

*Main> eval [] [(Fun 'f', (Var 'X', (Mul (VarLookup (Var 'X')) (Int 2))))] (Add (FunLookup (Fun 'f') (Int 3)) (Int 1))
7
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
misskwiz
Posts: 96
Joined: Wed Mar 21, 2007 6:19 am UTC

Re: Coding: Fleeting Thoughts

Postby misskwiz » Sat Oct 04, 2008 11:46 am UTC

Once in a while I like to try weird things in Python, normally more functional things that might not blend well with it, here's the latest attempt:

Code: Select all

#If you don't know, 'open', is the builtin function that opens files, and json.load takes a file object.
#Also all of the following code is Python 2.6.

def read_json(root):
    with Error(open, index_path(root), 'r') as openf:
        return openf.useOrElse(Option(None), Try(json.load)).get({})

The 'normal' python equivalent is:

Code: Select all

def old_read_json(root):
    index = {}
    try:
        with open(index_path(root), 'r') as openf:
                index = json.load(openf)
    except Exception:
        pass
    finally:
        return index

Yes, that's right! Option types! *everybody cheers*. Looking at the earlier code again, Error is a class that takes a function and it's arguments, and calls the function with them inside a try, except block and remembers the return value and if it had an exception. (I wrote it so both Option and Error are context managers so they work with 'with' statements). Then we call useOrElse on openf, which takes a default value, a function and although not shown here, more arguments to the function. useOrElse returns the default if the Option is None, or in this case, if the Error had an exception. If Option isn't None or Error didn't raise an exception, then it calls the function with it's data as the first argument. The function in question here is json.load, but it's wrapped in 'Try', which constructs a callable object that returns an Error. Finally, we call get({}) on the result of all of this. get is a method on both Option and Error which returns what the option or error is holding or the default, in this case an empty dictionary.

Here's the relevant option.py code, I removed all the methods on both types that aren't needed for understanding the snippet:

Code: Select all

_enter = lambda x: x.__enter__()
_exit = lambda x, t, v, tb: x.__exit__(t, v, tb)

class _OptionMixin(object):
    def __enter__(self):
        self.useCond(_enter)
        return self
   
    def __exit__(self, ttype, value, traceback):
        self.useCond(_exit, ttype, value, traceback)

class Option(_OptionMixin):
    def __init__(self, data=None):
        self.data = data

    def get(self, default=None):
        if self.data is None:
            return default
        else:
            return self.data

    def useCond(self, func, *args, **kwargs):
        if self.data is not None:
            func(self.data, *args, **kwargs)

    def useOrElse(self, default, func, *args, **kwargs):
        if self.data is None:
            return default
        else:
            return func(self.data, *args, **kwargs)

class Error(_OptionMixin):
    def __init__(self, func, *args, **kwargs):
        try:
            self.data = func(*args, **kwargs)
            self.exc = False
        except Exception as exc:
            self.data = exc
            self.exc = True

    def get(self, default=None):
        if self.exc:
            return default
        else:
            return self.data

    def useCond(self, func, *args, **kwargs):
        if self.exc is False:
            func(self.data, *args, **kwargs)

    def useOrElse(self, default, func, *args, **kwargs):
        if self.exc:
            return default
        else:
            return func(self.data, *args, **kwargs)

class Try(object):
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        return Error(self.func, *args, **kwargs)
I am currently enjoying the pathetic anger bread of a dissatisfied life.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Tue Oct 07, 2008 4:08 pm UTC

SBCL keeps surprising me at how fast it can be with numerical code (in this case some simple 4-op FM synthesis). It runs some of my code ~15x faster than the other implementions I have, and it doesn't seem to be consing when running the code... I wonder how fast it would be compared to C if I integrated the whole thing together.

User avatar
Xanthir
My HERO!!!
Posts: 5400
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Fri Oct 10, 2008 12:16 am UTC

Well, I finally broke down and tried out a javascript library. I pride myself on being able to do some astonishing things with pure CSS and trickery, and I try to be minimal with js when I do use it. However, I'd heard that Google is hosting a lot of popular js libraries now so your visitors are likely to have already cached the damn thing, so I threw my hat in and tried it out.

It was glorious.

Specifically, after messing around in the jQuery, Prototype, and Dojo tutorials, I decided on jQuery. Plus, several people on the CSSWG list mentioned using it, and what's the use of peer pressure if you don't cave to it? All I *needed* was a halfway decent removeClass function to fix an error in my current "click a thing to toggle show/hide for whatever comes after it" code, but I went ahead and tried out doing it all in jQuery. It was... wonderful. Stupid simple, and with all the browser inconsistencies ironed out by the library, all I had to was code and it all fit together. I transformed a small mess of CSS stylesheets (one of which got written into the page by Javascript, to ensure that it would only activate when js was actually enabled) and some custom JS code into just this:

Code: Select all

$(document).ready(function() {
   $("div.chapters").hide();
   $("div.head").click( function() {
      $(this).next("div.chapters").toggle();
      $(this).toggleClass("toggled-open");
      return false;
   });
});


Yes.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sun Oct 12, 2008 1:42 am UTC

Just for fun and laughs, I tried my hand at a simple trigram-based text creator tool. I fed it an arbitrary text found online: "Kalli, the esquimaux christian", and asked it for a thousand words.
Some excerpts:
Spoiler:
he said but very little, he seemed to understand better than
ever before. The last seizure was so sudden and violent, that he had been taken with him to us."

Spoiler:
Legacy to a Project
Gutenberg-tm work. The Foundation is a lake a little
distance from the person you received the work of desecration.

Spoiler:
Poor lad, he strain'd his eyes in vain,
Till tears began to issue
from the "winter's wind," and
fast-falling snow, by a Naturalist 3 0

Spoiler:
It has been observed by medical
men, that Esquimaux have but little stamina, and generally fail under
the College Chapel on the voyage from the ice
in Melville Bay, natives were seen from the "winter's wind," and
fast-falling snow, by a http://www.PGDP.net volunteer, David T. Jones, and the
Baptismal Service commenced.

Spoiler:
Do not copy, display, perform, distribute or redistribute this
electronic work, or any files containing a part of some epidemic, probably influenza,

Spoiler:
On entering the nave, "Whether he might cough there?" This
tendency to cough, arising from an ailment, the seeds of which the phrase "Project
Gutenberg" is associated

Spoiler:
The Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to
subscribe to our email newsletter to hear of your country in the rudiments of reading and writing, and to join the ship,


It also does a mean Shakespeare...
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
'; DROP DATABASE;--
Posts: 3284
Joined: Thu Nov 22, 2007 9:38 am UTC
Location: Midwest Alberta, where it's STILL snowy
Contact:

Re: Coding: Fleeting Thoughts

Postby '; DROP DATABASE;-- » Sun Oct 12, 2008 5:07 am UTC

Berengal wrote:
Spoiler:
Poor lad, he strain'd his eyes in vain,
Till tears began to issue
from the "winter's wind," and
fast-falling snow, by a Naturalist 3 0
I first read "naturalist 3.0", which actually rhymes.
poxic wrote:You suck. And simultaneously rock. I think you've invented a new state of being.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sun Oct 12, 2008 6:14 am UTC

That's what I did too. Also, I had to actually look up Act IV in the original text (The merry wives of windsor) to see that yes, it's nothing like this at all:
Spoiler:
ACT IV. SCENE I.

Windsor. A street

Enter MISTRESS QUICKLY

Enter MISTRESS ANNE PAGE as
a fairy, and OTHERS as the earth is
firm
that Falstaff is there. See what humour he is wronged.
PAGE. Here comes fair Mistress Anne!
ANNE. The dinner attends you, sir.
SLENDER. That's meat and drink to me at your back-door,
Mistress Ford, Master Brook; you shall
want none. I shall as soon quarrel at
it as to lay an amiable
siege to the vehemency of your
own, that I have seen the time with my heart, la! with my cudgel;
it shall bite upon my necessity. He loves the gallimaufry. Ford, perpend.
FORD. Love my wife!
PISTOL. With liver burning hot. Prevent, or go thou,
Like Sir Actaeon he, with Ringwood at thy heels.
O, odious is the focative
case, William?
WILLIAM. Genitive case?
EVANS. Ay.
WILLIAM. Genitive: horum, harum, horum.
QUICKLY. Vengeance of Jenny's case; fie on her! Never
name her, child, if she be otherwise, 'tis
labour
well bestowed. Exit

Yeah, I didn't think it made much sense, but sometimes there's only one possible word after a certain pair, corresponding to the only place in the original text that trigram was found, and you can get entire paragraphs of the original text with perhaps only a few modifications in the output. This was nothing like the original scene IV at all.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Mon Oct 20, 2008 12:45 am UTC

Debugging in various languages:

Java:
Set breakpoints and use the debugger to try to pinpoint exactly where you went wrong in the code. Often involves stepping through the code.

Python:
The point of failure is often obvious, and if it isn't, asking the interpreter a few times often tell you were. Add a print statement or two, then throw a few statements at the interpreter to see what they return/produce, compare with what they should produce, and you'll know what you did wrong.

Haskell:
Take a look at the source code. You will spot the bug, and you will fix it quickly this way.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Mon Oct 20, 2008 6:39 pm UTC

Berengal wrote:Debugging in various languages:

Java:
Set breakpoints and use the debugger to try to pinpoint exactly where you went wrong in the code. Often involves stepping through the code.

Python:
The point of failure is often obvious, and if it isn't, asking the interpreter a few times often tell you were. Add a print statement or two, then throw a few statements at the interpreter to see what they return/produce, compare with what they should produce, and you'll know what you did wrong.

Haskell:
Take a look at the source code. You will spot the bug, and you will fix it quickly this way.

APL:
ctrl-A; delete; start over
C:
Run it again; it only segfaults half the time.
:)
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

ediblespread
Posts: 33
Joined: Fri Jul 25, 2008 6:29 pm UTC

Re: Coding: Fleeting Thoughts

Postby ediblespread » Wed Oct 22, 2008 5:01 pm UTC

Haskell:
Take a look at the source code. You will spot the bug, and you will fix it quickly this way.


Depends. Generally read the error message first, and spot where you're either being a twat trying to feed a string into a char-type function (god, you have no idea how many people in my class are yet to realise that toLower will not work on their bloody strings, and it's their fault that it's broken and it's not 'stupid haskell'), or spot where you've forgotten to close a bracket (since it'll tell you the error is on line 2341, and you made the mistake on line 3.)

I like haskell. I barely know anything (hey, I've been here like 4 weeks now!), but it's so easy... to the point where I was just looking over Euler's problems, and looking at people's dozen-2dozen line solutions in various languages, and thought "wow, okay, I mean, my way was brute force, but for counting numbers its just so... easy."

Spoiler:

Code: Select all

euler1 = sum [ x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]


(and if anyone points out a problem in that code I'll cry!)

-Edibles

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Wed Oct 22, 2008 5:59 pm UTC

I was thinking more along the lines of bugs that aren't compiler errors, but it's interesting to note that when haskell programmers hear "bug" they think "compiler error". You're not the first one I've encountered (including myself).
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
sparkyb
Posts: 1091
Joined: Thu Sep 06, 2007 7:30 pm UTC
Location: Camberville proper!
Contact:

Re: Coding: Fleeting Thoughts

Postby sparkyb » Thu Oct 23, 2008 1:48 am UTC

Berengal wrote:Python:
The point of failure is often obvious, and if it isn't, asking the interpreter a few times often tell you were. Add a print statement or two, then throw a few statements at the interpreter to see what they return/produce, compare with what they should produce, and you'll know what you did wrong.


if it has an error, run in interactive mode and then when it has the error use pdb.pm() to get an interactive context at that spot and inspect the variables yourself.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Thu Oct 23, 2008 1:54 am UTC

sparkyb wrote:
Berengal wrote:Python:
The point of failure is often obvious, and if it isn't, asking the interpreter a few times often tell you were. Add a print statement or two, then throw a few statements at the interpreter to see what they return/produce, compare with what they should produce, and you'll know what you did wrong.


if it has an error, run in interactive mode and then when it has the error use pdb.pm() to get an interactive context at that spot and inspect the variables yourself.

Awesome! If I could put that in source code, I would put it in every except block I write.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

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

Re: Coding: Fleeting Thoughts

Postby EvanED » Thu Oct 23, 2008 6:46 am UTC

Berengal wrote:I was thinking more along the lines of bugs that aren't compiler errors, but it's interesting to note that when haskell programmers hear "bug" they think "compiler error". You're not the first one I've encountered (including myself).

I don't have any Haskell experience, but I've done a bit of programming in SML and the people in that community say about the same sort of thing. I agree somewhat, but I also think the Douglas Adams quote "The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at and repair" applies. The times when I have had logic errors that I've had to figure out have been some of my most painful debugging experiences. (Largely because the implementations of SML I've seen seem to suck balls.)

User avatar
MoD
Posts: 107
Joined: Sun Dec 30, 2007 4:55 pm UTC

Re: Coding: Fleeting Thoughts

Postby MoD » Fri Oct 24, 2008 1:56 am UTC

I am amazed at this hack I discovered for appending numbers to lists in Casio BASIC for programmable calculators. The code is thusly:

Code: Select all

1+Dim List 1
Seq(List 1[X - (X=Ans, X, 1, Ans, 1->List 1
77->List 1[Ans


If I understand this bit of voodoo correctly, it utilizes the sequence function (designed for geometric series, I believe) to iterate through the current incarnation of List 1, using X as a temp variable, and place that into a new, larger List 1. This is clearly not what the function was designed for, and along with the missing closing parentheses and brackets, it looks ridiculous enough to raise a WTF of prodigious magnitude if you ever come back to it later.
Last edited by MoD on Thu Jan 22, 2009 12:48 pm UTC, edited 1 time in total.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 18 guests