Coding: Fleeting Thoughts

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

Moderators: phlip, Moderators General, Prelates

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? » Sun Feb 13, 2011 12:34 am UTC

Thesh wrote:
joshz wrote:That ii thing would kind of annoy me if I saw it in code, tbh. i j k is a pretty established standard, and having to count the number of "i"s would quickly get impractical.


But consecutive letters in impractical if you have over 26 levels of nesting...


If you have over 26 levels of nesting, you've got bigger problems with your code than variable naming.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Rippy
Posts: 2101
Joined: Sun Jul 22, 2007 11:27 pm UTC
Location: Ontario, Can o' Duh

Re: Coding: Fleeting Thoughts

Postby Rippy » Sun Feb 13, 2011 12:46 am UTC

You, sir, name? wrote:
Thesh wrote:
joshz wrote:That ii thing would kind of annoy me if I saw it in code, tbh. i j k is a pretty established standard, and having to count the number of "i"s would quickly get impractical.


But consecutive letters in impractical if you have over 26 levels of nesting...


If you have over 26 levels of nesting, you've got bigger problems with your code than variable naming.

This is why I stand by i j k: if I find myself needing another loop variable after k, I put down the keyboard and take a long hard look at what I'm doing.

User avatar
joshz
Posts: 1466
Joined: Tue Nov 11, 2008 2:51 am UTC
Location: Pittsburgh, PA

Re: Coding: Fleeting Thoughts

Postby joshz » Sun Feb 13, 2011 1:13 am UTC

You, sir, name? wrote:If you have over 26 levels of nesting, you've got bigger problems with your code than variable naming.
hahahaha, awesome. sig'd.
You, sir, name? wrote:If you have over 26 levels of nesting, you've got bigger problems ... than variable naming.
suffer-cait wrote:it might also be interesting to note here that i don't like 5 fingers. they feel too bulky.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Sun Feb 13, 2011 2:31 am UTC

Roman numerals?

Code: Select all

for (int i = 0; i < 10; i++)
    for (int ii = 0; ii < 10; ii++)
        for (int iii = 0; iii < 10; iii++)
            for (int iv = 0; iii < 10; iii++)
                for (int v = 0; v < 10; v++)
                    for (int vi = 0; vi < 10; vi++)
                        for (int vii = 0; vii < 10; vii++)
                            for (int viii = 0; viii < 10; viii++)
                                for (int ix = 0; ix < 10; ix++)
                                    for (int x = 0; x < 10; x++)
                                        ; 

Actually, in cases like this, I usually just use more descriptive names.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

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? » Sun Feb 13, 2011 2:39 am UTC

C really spoils you with it's raw power. When I code python I am like... wait what, this algorithm is O(n^2) and n=5000, why isn't this taking order of seconds to finish?
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

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

Re: Coding: Fleeting Thoughts

Postby Thesh » Sun Feb 13, 2011 3:00 am UTC

A C# developer I worked with loved C# because you rarely had to write your own stuff.

Him: "They have this built in already"
Me: "Yeah, but it doesn't really do what you want"
Him: "Well, we'll change it so it does what we want"
Me: "But... The code to do exactly what you want is only 20 lines and will be faster"
Him: "But why reinvent the wheel?"

Happened with copy-paste code too.
Summum ius, summa iniuria.

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

Re: Coding: Fleeting Thoughts

Postby _Axle_ » Sun Feb 13, 2011 5:26 am UTC

@for loop varibles
If each for loop is independent of each other, I sometimes just tend to keep using i or ind for it. If the loop is for exact purposes, I tend to name it something less than 4 letters. ( 2x2 grid, vars : x,y or r,c ). Worst nested loop I made was 7 while loops deep <_<, I had to write a recursive algorithm ... without recursion, bleh!

@ C# vs C/C++
I would call myself a C/C++ programmer ( leaning towards more C-ish styles ). C# has some nice features, but how they implemented some of the .NET framework in it sucks. I tend to use C# for quick window GUIs. How is there no implicit typecast from float to double.... when all trig and sqrt functions defined in Math are only defined in doubles....... Why.
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

User avatar
chridd
Has a vermicelli title
Posts: 846
Joined: Tue Aug 19, 2008 10:07 am UTC
Location: ...Earth, I guess?
Contact:

Re: Coding: Fleeting Thoughts

Postby chridd » Sun Feb 13, 2011 7:29 am UTC

Rippy wrote:Now for my question.. (I will likely be plaguing this thread with Haskell questions for awhile). I'm trying to write a function to produce a [partly] randomly generated instance of a data type. So my thought was something like

Code: Select all

randomObj :: IO Obj
randomObj = do a <- randomRIO (0,10)
               return Obj (foo a) 0 --foo converts an int to the appropriate type

But this gives me errors. The function's trying to return Obj not IO Obj, and foo is being passed an IO Int rather than an Int. I'm out of ideas as to how to go about this.

Goddamn Haskell type system, I can appreciate your elegance and yet I can't yet totally make sense of you >_>.
You need parentheses around (Obj (foo a) 0); otherwise you're trying to pass the Obj constructor to return as its first argument and (foo a) and 0 as its second and third arguments. Otherwise it looks like it should be correct; the <- makes the IO Int a normal Int, and return is a function of type (in this case) a -> IO a.
~ chri d. d. /tʃɹɪ.di.di/ (Phonotactics, schmphonotactics) · she · Forum game scores
mittfh wrote:I wish this post was very quotable...

User avatar
hotaru
Posts: 1045
Joined: Fri Apr 13, 2007 6:54 pm UTC

Re: Coding: Fleeting Thoughts

Postby hotaru » Sun Feb 13, 2011 8:33 am UTC

_Axle_ wrote:How is there no implicit typecast from float to double.... when all trig and sqrt functions defined in Math are only defined in doubles....... Why.

i don't see why that's much of a problem... there are very few reasons to use a float over a double anymore.

Code: Select all

factorial product enumFromTo 1
isPrime n 
factorial (1) `mod== 1

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Coding: Fleeting Thoughts

Postby Sc4Freak » Sun Feb 13, 2011 10:06 am UTC

_Axle_ wrote:@for loop varibles
If each for loop is independent of each other, I sometimes just tend to keep using i or ind for it. If the loop is for exact purposes, I tend to name it something less than 4 letters. ( 2x2 grid, vars : x,y or r,c ). Worst nested loop I made was 7 while loops deep <_<, I had to write a recursive algorithm ... without recursion, bleh!

@ C# vs C/C++
I would call myself a C/C++ programmer ( leaning towards more C-ish styles ). C# has some nice features, but how they implemented some of the .NET framework in it sucks. I tend to use C# for quick window GUIs. How is there no implicit typecast from float to double.... when all trig and sqrt functions defined in Math are only defined in doubles....... Why.


Implicit cast from float to double works just fine in C#. The rules are the same as C/C++. Implicit float -> double is legal (since it's a widening conversion) but implicit double -> float is not.

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

Re: Coding: Fleeting Thoughts

Postby phlip » Sun Feb 13, 2011 10:09 am UTC

Sc4Freak wrote:The rules are the same as C/C++. [...] implicit double -> float is not.

C/C++ has implicit any-numeric-to-any-numeric conversion... whether it's getting bigger or smaller. You can implicitly convert a double as an unsigned char, and it won't blink.

Code: Select all

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

User avatar
Rippy
Posts: 2101
Joined: Sun Jul 22, 2007 11:27 pm UTC
Location: Ontario, Can o' Duh

Re: Coding: Fleeting Thoughts

Postby Rippy » Sun Feb 13, 2011 1:43 pm UTC

chridd wrote:You need parentheses around (Obj (foo a) 0); otherwise you're trying to pass the Obj constructor to return as its first argument and (foo a) and 0 as its second and third arguments. Otherwise it looks like it should be correct; the <- makes the IO Int a normal Int, and return is a function of type (in this case) a -> IO a.

Goddamnit, you're right, it works. This is C reflex telling me that "return" is special and not a normal function.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Sun Feb 13, 2011 7:18 pm UTC

FT: I'm certain there's a memory leak in my program. What's the best way to find it?

I've downloaded Valgrind, but all it gives me is a stack trace and a "leak summary". I'd like to know where the leaked memory is allocated, not how much of it there is. How would I do this? Is it possible?
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Sun Feb 13, 2011 7:53 pm UTC

Depending on the language, you might be able to get more information. If you're in C# or Java there are programs out there that can use the runtime's features to analyze memory better, I know we use something like this at work for C# and it can monitor objects that haven't or can't be deallocated because of leftover pointers/event handlers.

I'm not sure if you can do something like that in C/C++, usually you'd have to know at least the parts of code leaking memory. Though there might be something out there to do so, I haven't worked with them as much.

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

Re: Coding: Fleeting Thoughts

Postby _Axle_ » Sun Feb 13, 2011 8:41 pm UTC

For C++ ( using new, not malloc) , you can throw : _CrtDumpMemoryLeaks() at the end of your program to see the size and data of what wasn't deleted. It won't show line number of where, but you might be able to make a good guess at where it might occur if you know what is leaking.

If that isn't good enough, make your own memory manager and keep track of all allocations and record line numbers/files where and/or keep track of allocation number, so you know that the 43rd allocation never gets freed and track it.

@C# casting
My bad on that, its the double->float part that gets the error <_<. I still am not a fan of them not defining the math library for all basic data types, like the C/C++ math library.
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

bittyx
Posts: 194
Joined: Tue Sep 25, 2007 9:10 pm UTC
Location: Belgrade, Serbia

Re: Coding: Fleeting Thoughts

Postby bittyx » Sun Feb 13, 2011 10:41 pm UTC

Windowlicker wrote:Alright, cheers. I tend to enjoy habits, moving away from basing it at i is.. a large amount of effort. I've never seen the ii, iii thing before.. I quite like that. I'll give it a go.

On a slightly (entirely) unrelated note, how do web devs these days write their (x)html? I've seen a lot of advice on forums around the internet advising away from Dreamweaver, but one of my lecturers spent much of a lecture the other day telling us that manually typing html died out ages ago and all the "pros" use graphical tools like Dreamweaver.
I'm inclined to go with the forums, partly because when I used Dreamweaver it didn't seem very good, and partly because that particular lecturer doesn't seem to actually know about any of the things he talks about..


If I'm just doing some simple design stuff, I'll just find the file I need in Total Commander and hit F4, which opens the file in Notepad++ (my default editor in Windows). The same for CSS stuff etc. If I'm doing more serious PHP stuff, I'll either use Notepad++ or Eclipse PDT. I don't personally know a single web developer who knows his stuff and uses a WYSIWYG editor. And the people I know that use Dreamweaver are mostly just beginners/not very seriously interested in web dev stuff.

That said, most of the time I'll use some (very general) template if I'm starting from scratch (ie. a file.php with just basic stuff like document type, encoding, etc.) Also, using frameworks changes the workflow a bit, but still, you don't really need a graphical tool all that much, since you're gonna be checking your design in various browsers anyway. Just open the page you're working on in a few browsers and hit F5 each time you make a change. This is very important for bug fixing (to be more precise - Internet Explorer bug fixing).

Oh, one thing that really bothered me with Dreamweaver was how it handles UTF-8 - I've found that if the file you're writing doesn't contain a character that isn't in Latin-1 (Western European), you can't save it in UTF-8 - it just gets saved as Latin-1 no matter what you set as the encoding. Since my mother tongue is Serbian, and I make websites in this language, this has been *incredibly* annoying many times. And last but not least - Notepad++ is free, Eclipse as well. Dreamweaver costs a bunch of money and doesn't work like I want it to. For me, the choice is pretty clear, and I'm certainly not the only one.

Hope this helps at least somewhat! Cheers!

User avatar
Emu*
Posts: 689
Joined: Mon Apr 28, 2008 9:47 am UTC
Location: Cardiff, UK
Contact:

Re: Coding: Fleeting Thoughts

Postby Emu* » Sun Feb 13, 2011 11:27 pm UTC

Windowlicker wrote:manually typing html died out ages ago and all the "pros" use graphical tools like Dreamweaver. .

Bullshit.

Windowlicker wrote:that particular lecturer doesn't seem to actually know about any of the things he talks about..

Word.

Nowadays it's very unlikely that a website will not use something resembling a templating system, if not a complete CMS such as Drupal, Joomla/Mambo... You might be able to mock up a CMS template in Dreamweaver but the markup generated will not work elegantly across different browser and versions, will be semantically obtuse and usually inefficient.

In a pro environment, typically a Graphic Designer will mock up in photoshop or illustrator (or both), then the developer writes markup to produce that layout in an accessible, visually consistent, semantically good (for SEO) manner. This will involve editing HTML and CSS but in an editor which helps, code colouring, syntax highlighting, tag completion etc.
Cosmologicon wrote:Emu* implemented a naive east-first strategy and ran it for an hour, producing results that rivaled many sophisticated strategies, visiting 614 cells. For this, Emu* is awarded Best Deterministic Algorithm!

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Coding: Fleeting Thoughts

Postby Sc4Freak » Sun Feb 13, 2011 11:53 pm UTC

phlip wrote:
Sc4Freak wrote:The rules are the same as C/C++. [...] implicit double -> float is not.

C/C++ has implicit any-numeric-to-any-numeric conversion... whether it's getting bigger or smaller. You can implicitly convert a double as an unsigned char, and it won't blink.

Okay, wow. I've been away from C++ for way too long.

User avatar
b.i.o
Green is the loneliest number
Posts: 2519
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: Coding: Fleeting Thoughts

Postby b.i.o » Mon Feb 14, 2011 12:05 am UTC

Windowlicker wrote:On a slightly (entirely) unrelated note, how do web devs these days write their (x)html? I've seen a lot of advice on forums around the internet advising away from Dreamweaver, but one of my lecturers spent much of a lecture the other day telling us that manually typing html died out ages ago and all the "pros" use graphical tools like Dreamweaver.

Your lecturer is a moron. Do it by hand. Use a good editor with syntax highlighting.

If you want to get adventurous, you can write your HTML in a language like Haml, which then transforms into HTML and has a much nicer (imo) syntax. (Although it's primarily a templating language and is a lot more useful when used as one, I still use it when writing plain HTML.) I'd make sure you learn regular HTML/CSS first before switching to alternate syntaxes like Haml/Sass though.

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 Feb 14, 2011 12:56 am UTC

For editing HTML, I'd recomend Zen coding. It's a bunch of plugins for various editor that has a very nice input mode for html.
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
Link
Posts: 1419
Joined: Sat Mar 07, 2009 11:33 am UTC
Location: ᘝᓄᘈᖉᐣ
Contact:

Re: Coding: Fleeting Thoughts

Postby Link » Mon Feb 14, 2011 8:16 am UTC

TheChewanater wrote:FT: I'm certain there's a memory leak in my program. What's the best way to find it?

I've downloaded Valgrind, but all it gives me is a stack trace and a "leak summary". I'd like to know where the leaked memory is allocated, not how much of it there is. How would I do this? Is it possible?
First of all, make sure you compile with all the necessary debugging flags (if you're using GCC, -g should suffice, but I'd throw in -O0 for good measure). Without debugging symbols, you're not going to get any useful information whatsoever.

With the necessary debugging symbols included, try something like this:

Code: Select all

valgrind -v --leak-resolution=high --num-callers=50 --show-reachable=yes --leak-check=full <program>

Personally, I have an alias set up for that long line;

Code: Select all

alias valgrnd='valgrind -v --leak-resolution=high --num-callers=50 --show-reachable=yes --leak-check=full'

Windowlicker
Posts: 323
Joined: Wed Dec 23, 2009 6:57 pm UTC
Location: St Andrews, Scotland

Re: Coding: Fleeting Thoughts

Postby Windowlicker » Tue Feb 15, 2011 5:44 pm UTC

Thanks for all the earlier replies about the HTML and stuff, I kinda assumed the lecturer was being an idiot. I wish he'd tell us what the course we're currently on is actually about.. he's going through a strange mix of very elementary html and talking about abstract classes in Java. God knows.

And I'm kinda worried about starting to abuse this thread as a 'free help' sort of thing and just begging all the time, but I feel dumb as shit about this right now;

I'm trying to generate a set of 2d coordinates, which have to be unique pairs.. generating the numbers themselves is trivial enough obviously, but for some reason recently it's started to produce the same results for multiple sets. Here's the code that does the checking:

Spoiler:

Code: Select all

            do{
               matches = false;
               
               for(int i=1; i<totalItems-1; i++){
                  for(int j=i+1; j<totalItems; j++){
                     if((x[i]==x[j])&&(y[i]==y[j])){
                        matches = true;
                        x[j] = r.nextInt(board[0].length-1)+1;     //not sure if the -1/+1 cancel each other out, but this way keeps them within the bounds...
                        y[j] = r.nextInt(board[1].length-1)+1;     //and otherwise I have too much work to do to thoroughly test that bit
                     }
                  }
               }
            }while(matches);


Basically (I think) if it detects a matching pair it changes the second set and then starts the check all over again. It's probably not the most efficient way to run through it, but that's not so much a concern.. right now I just want it to work. Is there a problem with the logic in the check? And if so, what should I be doing?
I mean it could be a problem somewhere else, like the display functions, but my first reaction was that this is where it should be coming from...

User avatar
Rippy
Posts: 2101
Joined: Sun Jul 22, 2007 11:27 pm UTC
Location: Ontario, Can o' Duh

Re: Coding: Fleeting Thoughts

Postby Rippy » Tue Feb 15, 2011 6:18 pm UTC

More annoying Haskell questions:

What would be a good method for representing a grid in Haskell? Linked lists seem inefficient, but so do immutable arrays. Should it be mutable arrays then? I'll be doing pathfinding and other such things, so I have 2d arrays in mind, but maybe there's a more functional way to do it.

As infuriating as the type system is... I'm starting to really appreciate it. You spend a lot of time working out annoying type/syntax errors, but then very rarely do you run your program and not see it do what you expect.

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

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Tue Feb 15, 2011 7:00 pm UTC

For the most efficiency, you want mutation, I think. That means either ST or IO. You would end up with something with a type like Array (IORef (Array (IORef Data))). If you only need fast adjacent access, you can use zippers, which you would nest similarly to arrays.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

Re: Coding: Fleeting Thoughts

Postby _Axle_ » Tue Feb 15, 2011 8:15 pm UTC

Windowlicker wrote:And I'm kinda worried about starting to abuse this thread as a 'free help' sort of thing and just begging all the time, but I feel dumb as shit about this right now;


For one : The coding forum is generally a help forum . . . for coding. About this thread as the 'free help'. I generally thought this thread was more of a random posting/rant/whatever thread involving coding/languages, and the "It doesn't work" as more a help, though if you post anywhere, in whatever language, there is bound to be someone to help with it :).


.... and if you provide code, it is not so much "I don't know what is going on, hold my hand", its more "I made an attempt, but still a novice, any help?"
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

Windowlicker
Posts: 323
Joined: Wed Dec 23, 2009 6:57 pm UTC
Location: St Andrews, Scotland

Re: Coding: Fleeting Thoughts

Postby Windowlicker » Tue Feb 15, 2011 8:27 pm UTC

_Axle_ wrote:
Windowlicker wrote:And I'm kinda worried about starting to abuse this thread as a 'free help' sort of thing and just begging all the time, but I feel dumb as shit about this right now;


For one : The coding forum is generally a help forum . . . for coding. About this thread as the 'free help'. I generally thought this thread was more of a random posting/rant/whatever thread involving coding/languages, and the "It doesn't work" as more a help, though if you post anywhere, in whatever language, there is bound to be someone to help with it :).


.... and if you provide code, it is not so much "I don't know what is going on, hold my hand", its more "I made an attempt, but still a novice, any help?"

Thanks. My attitude towards posting on fora(ums) (or this one at least) seems slightly strange.. Even having been lurking for about two years, and recognising almost every name that posts here, whenever I get to hitting that "submit" button it all seems strangely large and above me. Ah well, I'm sure I'll man up some time.
And I maybe would've gone with the "it doesn't work" thread if I'd... remembered about it. I'm sure stickies become invisible just when you need them.

And for that code.. I think it was just an off-by-one error, starting the outer loop at 1 instead of 0. Oops.

User avatar
Briareos
Posts: 1940
Joined: Thu Jul 12, 2007 12:40 pm UTC
Location: Town of the Big House

Re: Coding: Fleeting Thoughts

Postby Briareos » Wed Feb 16, 2011 12:22 am UTC

Oh, Haskell. I was rereading LYAH on applicative functors and put together this one-liner for fun:

Code: Select all

main = (+) <$> readLn <*> readLn >>= print
Sandry wrote:Bless you, Briareos.

Blriaraisghaasghoasufdpt.
Oregonaut wrote:Briareos is my new bestest friend.

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

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Wed Feb 16, 2011 1:21 pm UTC

Applicative functors are crazy. My favorite new trick, which someone in #haskell pointed out to me a week ago, is using the (->) instance of Applicative on big records.

Code: Select all

data Big = Big {foo :: F, bar :: B}

doStuffWithBig = f <$> foo <*> bar
-- doStuffWithBig x = f (foo x) (bar x)

-- and to call it, doStuffWithBig (Big F B)
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
mister_m
Posts: 34
Joined: Fri Feb 04, 2011 2:51 am UTC

Re: Coding: Fleeting Thoughts

Postby mister_m » Thu Feb 17, 2011 4:40 am UTC

The current task I am working on is learning the vim editor and the C language. I decided to try to code up a linked list to learn how stuff works in C with a basic project. I'd like the linked list to be a usable data structure for myself and for others (doubtful, but bare with me), my question is, what features should the linked list have in order for it to be as usable as possible? Right now I am considering having a sort of 'free list' to keep track of what nodes are removed from the list so calls to malloc are minimized, and I am also considering somehow making it "thread safe" once I learn enough about threads/mutexes/semaphores to do something like that.

As far as basic linked list functionality goes here is what I am looking at for starters: ll.h
Spoiler:

Code: Select all


#ifndef LL_H_
#define LL_H_


/*This is a singly linked list implementation. It is very simple.
 *
 *The list has a dummy head node that simply points to the first element in the actual list.
 *This feature assists in the edge condition where we have to insert/remove at the beginning.
 *
 *
 *Two structs for our Linked List. The first holds the head of the list, and the size for easy access.
 *It also holds an array of pointers for a free list of nodes.(Still very //TODO)
 *The second struct holds a pointer to the data of an individual node, as well as a pointer to the next element.
 *in the list.
 *
 */

typedef struct{
    int list_size;
    struct ll_node *next_ptr;
} ll_head;

typedef struct{
        void *data;
        struct ll_node *next_ptr;
} ll_node;

/*Creates an empty linked list. Returns a pointer to the head*/
ll_head *ll_create_empty();

/*Free/Delete the entire list one node at a time.*/
void ll_free(ll_head *head);

/*Append node to the end of the linked list*/
//C has no default args, so...
ll_node *ll_append(ll_node *node);
ll_node *ll_append_data(ll_node *node, void *data);

/*'Prepend' to the beginning of list.*/
//Once again, no default args
ll_node *ll_prepend(ll_node *node);
ll_node *ll_prepend_data(ll_node *node, void *data);

/*Remove supplied node*/
int ll_remove(ll_node *node);

/*Get pointer to data at supplied node*/
void *ll_get_data_pointer(ll_node *node);

/*Get the last node's address given the head of the list */
ll_node *ll_last(ll_head *head);

/*Get the first node's address given the head of the list */
ll_node *ll_first(ll_head *head);

/*get the address of where the list's tail starts
 * (the node after the first(the head) node.
 */
ll_node *ll_tail(ll_head *head);

/*Get list size*/
int ll_size(ll_head *head);

/*Reverse List*/
ll_head *ll_reverse(ll_head *head);


/*Helper Macros*/


#endif /*LL_H_*/                                                                                                                     

Do you guys see any red flags with this yet? Is any basic linked list functionality missing? Advice on something to add? It is very WIP still, but I'd like to get it right.

User avatar
Briareos
Posts: 1940
Joined: Thu Jul 12, 2007 12:40 pm UTC
Location: Town of the Big House

Re: Coding: Fleeting Thoughts

Postby Briareos » Thu Feb 17, 2011 5:07 am UTC

No huge red flags, but a couple questions:

1) Why bother with struct ll_head? The classic way of doing a linked list is to just use the first node of the list rather than a distinct head node. I suppose you'll update the size in the head node as you add/delete other nodes? Do you anticipate needing the length of the list a lot for some reason? Otherwise it's straightforward to calculate, and dropping ll_head will save you a bunch of complication when it comes to implementation.

2) ll_get_data_pointer is a totally unnecessary function. If you have a pointer to a node (or a pointer to any struct), you access its fields like this:

Code: Select all

struct ll_node *x;
void *x_data = (*x).data
// this line is just syntactic sugar for the above
void *x_data = x->data

Did you come from a highly-encapsulated OO background, where you always wanted an accessor for a struct's data?
Sandry wrote:Bless you, Briareos.

Blriaraisghaasghoasufdpt.
Oregonaut wrote:Briareos is my new bestest friend.

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 Feb 17, 2011 9:39 am UTC

Briareos wrote:No huge red flags, but a couple questions:

1) Why bother with struct ll_head? The classic way of doing a linked list is to just use the first node of the list rather than a distinct head node. I suppose you'll update the size in the head node as you add/delete other nodes? Do you anticipate needing the length of the list a lot for some reason? Otherwise it's straightforward to calculate, and dropping ll_head will save you a bunch of complication when it comes to implementation.


I too question the use of this head structure. If you are going to have a head, you should make more use of it. Keep a pointer to the last element for quick appending, for example.
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 » Thu Feb 17, 2011 1:17 pm UTC

For extra fun, you can save the length of the list for each individual node, too. That way, the tail of the linked list is also another valid linked list.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

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 Feb 17, 2011 1:45 pm UTC

Iff you force the list structure to be immutable. Effectively creating a stack you can't deallocate popped members from.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Rippy
Posts: 2101
Joined: Sun Jul 22, 2007 11:27 pm UTC
Location: Ontario, Can o' Duh

Re: Coding: Fleeting Thoughts

Postby Rippy » Thu Feb 17, 2011 2:17 pm UTC

I dreamed about programming last night. I can't remember it all, but I was doing work-related programming, except it was in Haskell rather than VBscript (clearly a dream), and I was getting the type signature of a function wrong.

Yes, even in my dreams I'm having problems with the type system. >_>

(It was actually a weird feeling though. I can't remember what I was doing, but I woke up with the distinct feeling that whatever strange dreamed-up problem I was working on, I solved it.)

User avatar
mister_m
Posts: 34
Joined: Fri Feb 04, 2011 2:51 am UTC

Re: Coding: Fleeting Thoughts

Postby mister_m » Thu Feb 17, 2011 5:04 pm UTC

Briareos wrote:No huge red flags, but a couple questions:
1) Why bother with struct ll_head? The classic way of doing a linked list is to just use the first node of the list rather than a distinct head node. I suppose you'll update the size in the head node as you add/delete other nodes? Do you anticipate needing the length of the list a lot for some reason? Otherwise it's straightforward to calculate, and dropping ll_head will save you a bunch of complication when it comes to implementation.

You, sir, name? wrote:I too question the use of this head structure. If you are going to have a head, you should make more use of it. Keep a pointer to the last element for quick appending, for example.

I planned on eventually adding a pointer to my free list struct to the head node as well. Keeping track of the end of the list is also something that would make things quicker - at least faster than running through the list to get the size, or to find where the end is. I suppose this is more useful/makes more sense with a doubly linked list, where inserting and deleting at the beginning would be probably be less complicated with a dummy head node.

Briareos wrote:Did you come from a highly-encapsulated OO background, where you always wanted an accessor for a struct's data?

Straight from Java.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Sat Feb 19, 2011 4:10 am UTC

(For those not familiar with this year's FRC yet, STFW)

So, only two more meetings before FRC teams ship out their 'bots, and frustration is running higher than the top peg. Our robot's arm has a "home" position for when it's not picking stuff up and hanging them. We have a button to go to this position instead manually bringing the arm there. The problem is, every time that button is pressed, it goes to the wrong position, sometimes hitting itself. After shutting it off and inspecting the motor, chains, optical encoder, and everything else, the mechanical guys and the electrical guys determined that it was because of the programming guys. After all, mechanical guys and electrical guys never make mistakes. They were always complaining about how we programmers keep making mistakes, and had even (unsuccessfully) read the source code and tried to point out errors.

I looked through the code. I hadn't seen it before, since I was mostly working on a LISP interpreter for the robot while the mentor worked on actual useful stuff. There were a few unused variables, unsigned/signed int conversions, and magic numbers, but nothing seemed particularly wrong. I tried fixing the signed-ness, with no luck. A mentor commented out a call to get the encoder value, which wasn't used since it was called again right after that. It now seemed to go in the opposite direction. Very confused, I tried calling that twice and averaged their results (it wasn't a const member function, by the way). Still not quite right.

Then I noticed that the more the motor moved the more inaccurate it would be. The solution seemed obvious - the encoder gives the number of ticks since it was last called, not since it was started. I quickly coded up a solution that just adds up all of the calls to get the current position, deployed, and restarted the robot. After waiting the five minutes for it to start up and load the module (this is why I wanted a LISP interpreter), I moved the arm up, and hit the "home" button. The arm flew back down, nearly damaging our electronics that a former teammate suggested we place right in front of the arm (luckily it was covered in plexiglass, so it's perfectly fine).

I decided that I couldn't solve this problem, and went to work on the minibot. After being cut by my own creation, I went to see how things were going with the main robot. On my way, one of the electrical guys told me that they solved the problem - the mechanical guys had put the motor too close to the encoder, and noise from it was messing it up. When I got there, the mechanical guys said the electrical guys had put the encoder too close to the motor. Apparently, someone in one group or another hadn't thought things through very well. I facepalmed in my mind and informed them that they would never make it as programmers.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
Rippy
Posts: 2101
Joined: Sun Jul 22, 2007 11:27 pm UTC
Location: Ontario, Can o' Duh

Re: Coding: Fleeting Thoughts

Postby Rippy » Sun Feb 20, 2011 7:15 pm UTC

Ugh, trying to write a simple graphical program in Haskell is turning out to be extremely frustrating. It's like the way I know how to do it is awful, and the good way to do it uses fancy features that I don't understand. The only Haskell SDL tutorial I've found is a port of some C++ tutorials, which means that none of the Haskell code is explained.

User avatar
hotaru
Posts: 1045
Joined: Fri Apr 13, 2007 6:54 pm UTC

Re: Coding: Fleeting Thoughts

Postby hotaru » Mon Feb 21, 2011 3:30 pm UTC

someone apparently has way too much time on their hands, but this is kinda neat: http://dis.4chan.org/read/prog/1298263487
[imath]\def\I#1{#1}\def\A#1#2{#2{#1}}\def\Set#1#2{\def#2{\A{#1}}}\def\Infix#1#2#3{#3{#1{#2}}}\def\DefI#1#2{\def#1{\Infix#2}\def#2}\def\L#1#2{#1}\def\R#1#2{#2}\def\T#1{#1\L}\def\F#1{#1\R}\def\PBool#1{#1{True}{False}}\def\Not#1{#1\F\T}\def\And#1#2{#1{#2}\F}\def\Or#1#2{#1\T{#2}}\def\Xor#1#2{#1{#2\Not}{#2}}\def\EqB#1#2{#1{#2}{#2\Not}}\def\Maj#1#2{#1{#2\Or}{#2\And}}\def\CompB#1#2#3#4#5{#1{#2\I{#4}{#3}}{#2\I{#5}{#4}}}\def\P#1#2#3#4{#3{#4{#1}}{#4{#2}}}\def\N#1#2{\T}\DefI\.\PairP#1#2#3{#3{\P{#1}{#2}}}\Set\N\Nil\def\List{\Nil\.}\def\Left#1{#1\L}\def\Right#1{#1\R}\def\Null#1{#1\L{\L\F}}\def\Lone#1{#1\L\Null}\def\Last#1{\Lone{#1}\I{#1\R}{#1\L\Last}}\List\T\Set\NegOne\List\F\Set\0\List\F\.\T\Set\1\def\ShiftR#1{\Lone{#1}\I{\A{#1}}{#1\L}}\DefI\NB\NBP#1#2{\Lone{#1}\And{\EqB{#2}{#1\R}}\I{\A{#1}}{\PairP{#1}{#2}}}\def\PBin#1{\Null{#1}\I{}{#1\L\PBin#1\R\I10}}\DefI\=\EqIP#1#2{#1\R\EqB{#2\R}\And{\Lone{#1}\And{\Lone{#2}}\Or{\Lone{#1}\Not\And{\Lone{#2}\Not}\And{\ShiftR{#1}\={\ShiftR{#2}}}}}}\DefI\CompI\CompIP#1#2#3#4#5{\Lone{#1}\And{\Lone{#2}}\I{#1\R\CompB{#2\R}{#5}{#4}{#3}}{\ShiftR{#2}{\ShiftR{#1}\CompIP}{#3}{#1\R\CompB{#2\R}{#3}{#4}{#5}}{#5}}}\def\<#1#2{\CompI{#1}{#2}\F\F\T}\def\AddC#1#2#3{\Lone{#1}\And{\EqB{#3}{#1\R}}\I{\A{#2}}{\Lone{#2}\And{\EqB{#3}{#2\R}}\I{\A{#1}}{\Maj{#3}{#1\R}{#2\R}{\ShiftR{#2}{\ShiftR{#1}\AddC}}\NB{\Xor{#3}{#1\R}\Xor{#2\R}}}}}\def\+#1#2{#2\AddC{#1}\R}\1\+\1\Set\2\2\+\1\Set\3\3\+\1\Set\4\4\+\1\Set\5\5\+\1\Set\6\6\+\1\Set\7\7\+\1\Set\8\8\+\1\Set\9\9\+\1\Set\Ten\def\OComp#1{\Null{#1}\I{\Nil}{#1\L\OComp\.{#1\R\Not}}}\def\Neg#1{\OComp{#1}\+\1}\def\-#1#2{#2\OComp\AddC{#1}\L}\DefI\*\TimesP#1#2{\Lone{#1}\I{#1\R\I{\Neg{#2}}{\0}}{#1\R\I{#1\L\TimesP{#2}\NB\F\+{\A{#2}}}{#1\L\TimesP{#2}\NB\F}}}\def\QRPos#1#2{\Lone{#1}\I{#1\R\I{\NegOne\.{\-{#2}\1}}{\0\.\0}}{\ShiftR{#1}\QRPos{#2}\Set\PrevQR\PrevQR\Right\NB{#1\R}\Set\NewR\NewR\<{\A{#2}}\I{\PrevQR\Left\NB\F\.\NewR}{\PrevQR\Left\NB\T\.{\NewR\-{\A{#2}}}}}}\DefI\QR\QRP#1#2{\Last{#2}\I{\Neg{#2}{\Neg{#1}\QRPos}\Set\PrevQR\PrevQR\Left\.{\PrevQR\Right\Neg}}{\={#2}\0\I{\OhShi}{\QRPos{#1}{#2}}}}\def\/#1#2{\QR{#1}{#2}\Left}\def\Mod#1#2{\QR{#1}{#2}\Right}\def\Fact#1{\<{#1}\2\I{\1}{\-{#1}\1\Fact\*{\A{#1}}}}\DefI\At\AtP#1#2{\={#2}\0\I{#1\R}{\-{#2}\1{#1\L\AtP}}}\List{\A9}\.{\A8}\.{\A7}\.{\A6}\.{\A5}\.{\A4}\.{\A3}\.{\A2}\.{\A1}\.{\A0}\Set\Digits\def\PDecQR#1{#1\L\Lone\I{}{#1\L\PDecPos}\Digits\At{#1\R}\I}\def\PDecPos#1{\Ten{\QRPos{#1}}\PDecQR}\def\PDec#1{\<{#1}\0\I{-\Neg{#1}\PDecPos}{\PDecPos{#1}}}[/imath]

Code: Select all

\def \Collatz #1{
  \= {#1} \1 \I { \1 } {
    \Mod {#1} \2 \= \0 \I {
      \/ {#1} \2 \Collatz
    }
    {
      \* {#1} \3 \+ \1 \Collatz
    }
  }
}

[imath]\def\Collatz#1{\={#1}\1\I{\1}{\Mod{#1}\2\=\0\I{\/{#1}\2\Collatz}{\*{#1}\3\+\1\Collatz}}}[/imath][imath]\7 \Collatz \PDec[/imath]

Code: Select all

factorial product enumFromTo 1
isPrime n 
factorial (1) `mod== 1

Dr. Willpower
Posts: 197
Joined: Wed May 28, 2008 3:55 pm UTC

Re: Coding: Fleeting Thoughts

Postby Dr. Willpower » Thu Feb 24, 2011 6:08 pm UTC

Just wrote this and realized how ridiculous it looked.

Code: Select all

if (good) if (entry.getInDeg() != temp.getInDeg()) return null; else return temp;


Maybe should try this?

Code: Select all

if (good)
    return (entry.getInDeg() != temp.getInDeg())? null : temp;


Probably this way?

Code: Select all

if (good)
    if (entry.getInDeg() != temp.getInDeg())
        return null;
    else
        return temp;
Image
Hat me, bro

User avatar
joshz
Posts: 1466
Joined: Tue Nov 11, 2008 2:51 am UTC
Location: Pittsburgh, PA

Re: Coding: Fleeting Thoughts

Postby joshz » Thu Feb 24, 2011 8:49 pm UTC

I'd add in braces if I were you.

Code: Select all

if (good){
    if (entry.getInDeg() != temp.getInDeg())
        return null;
    else
        return temp;
}
You, sir, name? wrote:If you have over 26 levels of nesting, you've got bigger problems ... than variable naming.
suffer-cait wrote:it might also be interesting to note here that i don't like 5 fingers. they feel too bulky.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 12 guests