• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

irongear

Neo Member
Hello guys, i have assignment for converting binary numbers to decimal in java and i did write the code but want any feedback from you guys if i can make the code more efficient or if i did something that would reduce points from the assignment.

Code:
import java.util.Scanner;
 
public class ConvertBinary {
 
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a four, or more, digit binary number: ");
        String Binary = input.nextLine();
        int decimal = convertToDecimal(Binary);
        System.out.println("The binary number you have chose equals this in decimal:  "+ decimal);
          
    }
 
    private static int convertToDecimal(String binary) {
        final int base = 2;      
        int decimal = 0;
        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '0') {
                
                decimal += 0 * Math.pow(base, binary.length() - i - 1);
            } else if (binary.charAt(i) == '1') {
                decimal += 1 * Math.pow(base, binary.length() - i - 1);
            } else {
                
                System.out.println("Use the number one and/or zero please");
                     
            }

        }       
        return decimal;

    }
}

the example we were given was this:

Enter a four digit binary number (e.g. "0111")
> 0101
0101 converted to decimal is 5


**For the new page

Why are you multiplying by 0 (or doing anything for the "0" case)?

I'd probably write a recursive function.

to be honest i don't know how to do a recursive function i will look at up
 

ssharm02

Banned
There are three elements within the array (quarters, nickles and dimes)

i have to check the value for each to see if there are more than 1 of each type. And print Quarters or quarter, or dimes or dime etc etc

i cant get it to work plz help
 

dabig2

Member
There are three elements within the array (quarters, nickles and dimes)

i have to check the value for each to see if there are more than 1 of each type. And print Quarters or quarter, or dimes or dime etc etc

i cant get it to work plz help

Code? Language? Are we talking an array full of class objects (like a Coin class)?
 

JesseZao

Member
**For the new page



to be honest i don't know how to do a recursive function i will look at up

It's just a different way to handle a repetitive task. Sometimes it's easier to read than a loop. I could write an example when I get home.

A recursive function just keeps calling itself until it hits an end case.
 

irongear

Neo Member
It's just a different way to handle a repetitive task. Sometimes it's easier to read than a loop. I could write an example when I get home.

A recursive function just keeps calling itself until it hits an end case.

Showing me an example would be absolutely great! i saw a video explaining it but it seemed confusing, maybe an example with the binary and decimal conversion would make it easier to understand
 

ssharm02

Banned
Code? Language? Are we talking an array full of class objects (like a Coin class)?

no this is a very simple program, just one main class, one custom exception class and one test class to test the out put. User enters the the coin amount and it is divided/rounded up or down into quarters/dimes or nickle

final out put should look like this

54 cents requires 2 quarters and 1 nickle

and not
54 cents requires 2 quarters 0 dimes and 1 nickles etc etc
 

JeTmAn81

Member
no this is a very simple program, just one main class, one custom exception class and one test class to test the out put. User enters the the coin amount and it is divided/rounded up or down into quarters/dimes or nickle

final out put should look like this

54 cents requires 2 quarters and 1 nickle

and not
54 cents requires 2 quarters 0 dimes and 1 nickles etc etc

You could loop through the denomination array, subtracting the highest possible denomination from the total (without going negative) and incrementing a count for that denomination.

Then once your total hits zero or no denominations can be subtracted without going negative, you're done.

If you don't want to print out denominations which weren't used, just put an if statement requiring a count of at least one in order to be printed.
 

dabig2

Member
no this is a very simple program, just one main class, one custom exception class and one test class to test the out put. User enters the the coin amount and it is divided/rounded up or down into quarters/dimes or nickle

final out put should look like this

54 cents requires 2 quarters and 1 nickle

and not
54 cents requires 2 quarters 0 dimes and 1 nickles etc etc

Ah ok. There's a bunch of different ways. Here's a rough algorithm of how to convert iteratively without your constraints:

For example, take 110 cents.
Code:
int input = 110;
String answer =  "" + input + " cents requires ";
[B]Step 1: Find max number of quarters[/B]
[INDENT]int quarters = input / 25;[/INDENT]
This will give you 4. Now append this fact to your answer string.

[B]Step 2: Find max number of dimes[/B]
[INDENT]int dimes = (input - (quarters * 25)) / 10;[/INDENT]
This gives you 1. Append this fact to your answer string. 

[B]Step 3: Find max number of nickels[/B]
[INDENT]int nickels = (input - (quarters * 25) - (dimes * 10) / 5;[/INDENT]
This gives you 0. So don't append anything to the string. *Smells like an if statement right?*

[B]Step 4: Find max number of pennies[/B]
[INDENT]int pennies = (input - (quarters * 25) - (dimes * 10) - (nickels * 5) / 1;[/INDENT]
This again gives you 0. So don't append anything to the string. 

[B]Final step: Print string out[/B]

Dirty as hell algorithm with zero optimization, but the gist should be clear on how it works and how to make it work way more efficiently.

SO, if you absolutely have to use an array, then I would do it using an array of size 4 to represent the quarters, dimes, nickels, and pennies slots. Then do the same type of iterative procedure where instead of appending to the string, you place the number of each coin in its respective spot in the array. Like arr[0] = 4 for 4 quarters. arr[1] = 1 for 1 dime and so on. Then after you've converted the input into its base coinage, just read out the array iteratively where again you put an if statement to make sure you don't read out any coins that have a 0.

A more "fun" way of doing this assignment would be recursion. But I'll leave that up to you if you want to pursue that. Converting the iterative procedure I posted above to recursive code is a nice learning exercise in itself.
 

JesseZao

Member
Haven't written in Java in a while, but here's a crude idea similar to what you started with.

Code:
private static int binaryToDecimal(String input) {
    
    int output = 0;
    
    if (input == null || input.isEmpty()) {     
        System.out.println("Invalid input. Enter a binary number."); //or throw exception here            
    } 
    else {
        for (int n = input.length(); n > 0; n--) {
            if (input.charAt(n - 1) == '1') {
                output += Math.pow(2, input.length() - n);
            } 
            else if (input.charAt(n - 1) != '0'){
                System.out.println("Invalid input. Enter a binary number."); //or throw exception here                  
                output = 0;
                n = 0; // or break;
            }        
        }
    }
    
    return output;    
}

A recursive example would be a little less helpful if you aren't supposed to be using that style, but here's a basic example. It sums all of the digits in a positive integer.

Code:
public static int sumDigits(int number) {
    return (number <= 0) ? 0
                         : (number % 10) + sumDigits(number / 10);
}


// if you want to allow negative ints

public static int sumDigits(int number) {
    return (number < 0) ? sumDigits(-number)
                        : (number == 0) ? 0
                                        : (number % 10) + sumDigits(number / 10);
}

If you're interested in playing around with recursive functions, I found a simple site while in one of my first Java classes that lets you test out algorithms and recursion to solve coding exercises: CodingBat.com. ProjectEuler.net is another fun one.
 

Two Words

Member
Hello guys, i have assignment for converting binary numbers to decimal in java and i did write the code but want any feedback from you guys if i can make the code more efficient or if i did something that would reduce points from the assignment.

Code:
import java.util.Scanner;
 
public class ConvertBinary {
 
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a four, or more, digit binary number: ");
        String Binary = input.nextLine();
        int decimal = convertToDecimal(Binary);
        System.out.println("The binary number you have chose equals this in decimal:  "+ decimal);
          
    }
 
    private static int convertToDecimal(String binary) {
        final int base = 2;      
        int decimal = 0;
        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '0') {
                
                decimal += 0 * Math.pow(base, binary.length() - i - 1);
            } else if (binary.charAt(i) == '1') {
                decimal += 1 * Math.pow(base, binary.length() - i - 1);
            } else {
                
                System.out.println("Use the number one and/or zero please");
                     
            }

        }       
        return decimal;

    }
}

the example we were given was this:

Enter a four digit binary number (e.g. "0111")
> 0101
0101 converted to decimal is 5

As somebody stated, it is much easier to do this recursively like so:

Code:
public static int bin2Dec(String binaryString){
		if (binaryString.length() == 0)
			return 0;
		else
			return 2 * bin2Dec(binaryString.substring(0, binaryString.length()-1)) + (binaryString.charAt(binaryString.length()-1) - 48);
	}

Here's why it works. If the string is empty, it returns 0. If the string is not empty, it returns 2 times the result of recursively calling it with 1 letter removed, plus the value of the smallest digit. Think of it this way.

111 = 2 * 11 + 1 = 110 + 1 = 111

101010 = 2* 10101 + 0 = 101010 + 0 = 101010

The recursion makes the string smaller and smaller until it is empty and returns 0.
 

ssharm02

Banned
thanks a lot fellas really appreciate the help. already a day late 10% penalty gotta get the print statement working asap


any good resources for learning javascript?
 

JeTmAn81

Member
As somebody stated, it is much easier to do this recursively like so:

Code:
public static int bin2Dec(String binaryString){
		if (binaryString.length() == 0)
			return 0;
		else
			return 2 * bin2Dec(binaryString.substring(0, binaryString.length()-1)) + (binaryString.charAt(binaryString.length()-1) - 48);
	}

Here's why it works. If the string is empty, it returns 0. If the string is not empty, it returns 2 times the result of recursively calling it with 1 letter removed, plus the value of the smallest digit. Think of it this way.

111 = 2 * 11 + 1 = 110 + 1 = 111

101010 = 2* 10101 + 0 = 101010 + 0 = 101010

The recursion makes the string smaller and smaller until it is empty and returns 0.

I must say, your recursive solution may use less code but it is not easier to understand than the iterative solution, nor is a recursive solution typically preferred when an iterative one will do.
 
any good resources for learning javascript?
Well, depends what you want to learn. MDN is the defacto place for general documentation of all things web: https://developer.mozilla.org/en-US/docs/Web/JavaScript. Then there are free books like http://eloquentjavascript.net/ (which doesn't seem to cover ES2015 yet, though). Then there's this awesome list of JavaScript stuff: https://github.com/sorrycc/awesome-javascript and https://github.com/ericelliott/essential-javascript-links

Or just start writing code and come join us in the Web Dev thread when you need help :) http://www.neogaf.com/forum/showthread.php?t=756776&page=26
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
any good resources for learning javascript?

Javascript for Kids isn't a bad book for a beginners crash-course on keywords and stuff, but it assumes you have no prior programming knowledge.
 
I must say, your recursive solution may use less code but it is not easier to understand than the iterative solution, nor is a recursive solution typically preferred when an iterative one will do.

I tend to agree. I think the iterative solution is better here. Although not the original iterative solution. I would do something like:

Code:
private static int convertToDecimal(String binary) {
        int decimal = 0;
        int factor = 1;
        for (int i = binary.length()-1; i >= 0; --i) {
            if (binary.charAt(i) == '1')
                decimal += factor;
            factor *= 2;
        }       
        return decimal;

    }
 

Koren

Member
Why not multiply decimal by 2 at each step and get rid of factor? That would be simpler, and you don't need to iterate in reverse...

Edit: in case I'm not clear enough:
Code:
private static int convertToDecimal(String binary) {
        int decimal = 0;
        for (int i = 0; i<binary.length(); ++i) {
            decimal *= 2
            if (binary.charAt(i) == '1')
                decimal += 1;
        }       
        return decimal;
}

(or did I missed something?)

I must say, your recursive solution may use less code but it is not easier to understand than the iterative solution
In this case, I agree (and I'm not convinced that it's shorter either) but...

nor is a recursive solution typically preferred when an iterative one will do.
... that make me wonder... What is the state or tail-recursion optimization in Java? I'm completely out of touch, and remember it was only barely possible with JIT, is it still the case?
 

ssharm02

Banned
just learning javascript. For an assignment I have to create a text box, once the user types something in the text box and clicks the add button, the information should be sent to a table. I was wondering how to go about this. Can you please give me some pointers
 
Why not multiply decimal by 2 at each step and get rid of factor? That would be simpler, and you don't need to iterate in reverse...

Edit: in case I'm not clear enough:
Code:
private static int convertToDecimal(String binary) {
        int decimal = 0;
        for (int i = 0; i<binary.length(); ++i) {
            decimal *= 2
            if (binary.charAt(i) == '1')
                decimal += 1;
        }       
        return decimal;
}

(or did I missed something?)

Ahh yea that works, also simpler.
 
Ok so I just want to check another thing about inheritance.

Lets say I have

Code:
Class Creauture()
{
private:
    int strength;

public:
  void setStrength(int s);
  int getStrenght(); 

};

Class Oingo: public Creature
{


}

It would not inherit the private member variable strength, but would inherit set/getStrength. So what happens if I do this:

Oingo o1();

o1.setStrength(7);
o1.getStrenght();
 
Ok so I just want to check another thing about inheritance.

Lets say I have

Code:
Class Creauture()
{
private:
    int strength;

public:
  void setStrength(int s);
  int getStrenght(); 

};

Class Oingo: public Creature
{


}

It would not inherit the private member variable strength, but would inherit set/getStrength. So what happens if I do this:

Oingo o1();

o1.setStrength(7);
o1.getStrenght();

No. It inherits everything, the compiler just won't let you use it. It's still there, the base class can still use it internally, it's purely the compiler throwing up an error and saying "no stop" even though it could let you access it if it really wanted to.

It might be a subtle distinction, but it's important. Consider this code:

Code:
// What do you think sizeof(A) equals?
class A { private: int x; };

// What do you think sizeof(B) equals?
class B : public A { };

To answer your question, assuming those methods do what they sound like, o1.getStrength() returns 7.
 
No. It inherits everything, the compiler just won't let you use it. It might be a subtle distinction, but it's important. Consider this code:

Code:
// What do you think sizeof(A) equals?
class A { private: int x; };

// What do you think sizeof(B) equals?
class B : public A { };

To answer your question, assuming those methods do what they sound like, o1.getStrength() returns 7.

Ok that's what I thought it would return. So then, it inherits it. You say the compiler won't let me use it. But I sort of can use it as long as I use the base classes public functions to do it, right?
 
Ok that's what I thought it would return. So then, it inherits it. You say the compiler won't let me use it. But I sort of can use it as long as I use the base classes public functions to do it, right?

Right. But I would say you're not really using "the strength variable", you're using "the Creature class". Maybe Creature decides to change its implementation so it's not using an int variable, but instead it's storing the strength in a file somewhere (stupid thing to do, but possible nonetheless).

A person using the Creature class doesn't know about the private variables, or even that they exist. They just know that if they call setStrength() and getStrength() it will work as expected.
 
Right. But I would say you're not really using "the strength variable", you're using "the Creature class". Maybe Creature decides to change its implementation so it's not using an int variable, but instead it's storing the strength in a file somewhere (stupid thing to do, but possible nonetheless).

A person using the Creature class doesn't know about the private variables, or even that they exist. They just know that if they call setStrength() and getStrength() it will work as expected.

Huh neat. So look like I just might want to make strength a protected variable and call it a day.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
just learning javascript. For an assignment I have to create a text box, once the user types something in the text box and clicks the add button, the information should be sent to a table. I was wondering how to go about this. Can you please give me some pointers

Assuming this is all on the same page, you need:

A place to input text.
An event handler attached to an element that will serve as your button. You can use this tag as well.
A way to find and extract the information in the textbox.
Then create your table and display it to the page.

Honestly, you should try looking around first before asking for help. If you don't learn how to ask Google the right questions, you're going to have a very rough time programming. W3school will cover most of the rudimentary tasks you'll be expected to do with HTML/CSS/JavaScript.
 

JeTmAn81

Member
Assuming this is all on the same page, you need:

A place to input text.
An event handler attached to an element that will serve as your button. You can use this tag as well.
A way to find and extract the information in the textbox.
Then create your table and display it to the page.

Honestly, you should try looking around first before asking for help. If you don't learn how to ask Google the right questions, you're going to have a very rough time programming. W3school will cover most of the rudimentary tasks you'll be expected to do with HTML/CSS/JavaScript.

This is the right way to approach a programming problem. Break it into the smallest bits you can discern, then Google each bit. Once you understand the individual bits, Google how to put them together if necessary.
 

ssharm02

Banned
Assuming this is all on the same page, you need:

A place to input text.
An event handler attached to an element that will serve as your button. You can use this tag as well.
A way to find and extract the information in the textbox.
Then create your table and display it to the page.

Honestly, you should try looking around first before asking for help. If you don't learn how to ask Google the right questions, you're going to have a very rough time programming. W3school will cover most of the rudimentary tasks you'll be expected to do with HTML/CSS/JavaScript.

thanks for the help, for most of the core computer science stuff i was using books. but javascript is kind of hard :/

I actually broke the problem down before you typed in that. Thanks though much appreciated
 

Ambitious

Member
What do you guys do with outdated tech/programming books you don't need anymore? I recently found two ancient iOS 5 programming books in my shelf.

Usually, when I want to get rid of books, I first try to sell them, and donate them to the local library if I can't find a buyer. But I'm not sure what to do in this specific case. Who would ever need an iOS 5 programming book in this time and age? It's useless.

The obvious alternative is to just throw it away, but I just don't like the thought of simply tossing a book into the trash. But then again, I don't really have any other options, do I?
 

V_Arnold

Member
thanks for the help, for most of the core computer science stuff i was using books. but javascript is kind of hard :/

I actually broke the problem down before you typed in that. Thanks though much appreciated

Also, if you do not want to pull hairs out, you can just do something like

//Edit: gotta work a bit on this one, too many grammar, sec :p
//Edit2: here is a version that is rudimentary, but at least works:

Code:
<table id="dataplaceholder">
<tr><td></td></tr>
</table>

<input type="text" id="theinput">
<button onclick="send()">Add it</button>

<script>
    function send() {
document.getElementById("dataplaceholder").insertRow(-1).insertCell(-1).innerHTML=document.getElementById("theinput").value;
}
    </script>
 

upandaway

Member
What do you guys do with outdated tech/programming books you don't need anymore? I recently found two ancient iOS 5 programming books in my shelf.

Usually, when I want to get rid of books, I first try to sell them, and donate them to the local library if I can't find a buyer. But I'm not sure what to do in this specific case. Who would ever need an iOS 5 programming book in this time and age? It's useless.

The obvious alternative is to just throw it away, but I just don't like the thought of simply tossing a book into the trash. But then again, I don't really have any other options, do I?
My uni's CS library is full of books like that, that might be an option
 
What do you guys do with outdated tech/programming books you don't need anymore? I recently found two ancient iOS 5 programming books in my shelf.

Usually, when I want to get rid of books, I first try to sell them, and donate them to the local library if I can't find a buyer. But I'm not sure what to do in this specific case. Who would ever need an iOS 5 programming book in this time and age? It's useless.

The obvious alternative is to just throw it away, but I just don't like the thought of simply tossing a book into the trash. But then again, I don't really have any other options, do I?

They work as nice doorsteps in dry (not DRY) environments. Also funny paper weights. Maybe use them as coloring books
 

Somnid

Member
After mucking around in Rust on and off over the last few months I think I've decided I really don't like their syntax. Like why do static methods need a different operator :):) than instance methods (.)? I'm somewhat okay with implicit return values but why is this the preferred way of doing it (seems easy to fat-finger and less readable to me)? More superficially I've never liked lower_snake_case but I guess that's more personal. Also, I'm not sure I like the idea of macros. I understand why people would want them but adding meta-code to get magic syntax makes things very hard to understand. I'd rather just write things out long ways until the core syntax can handle it. Also, while nothing unique to Rust they love the rename everything, interfaces are "traits", static methods are "associated functions", variables are "bindings" etc. Not sure why languages do this, it just increases the learning curve but gains nothing.

Still, Rust has a lot of interesting things going for it that I like. Cargo is nice, it's fast and it does prevent stupid and more subtle mistakes and has decent error messages when you do.

Swift seems to have some similarities, I haven't written much in it but it seems "cleaner." Maybe someone will give it a real Windows port.
 

V_Arnold

Member
I would not use Swift when I could just use Javascript instead. In fact, I mostly do Javascript for everything now, but I still eye Rust from time to time, to get that native hotness.

Cause even with its issues, its certainly not like C : D
 

Somnid

Member
C++ does the same thing.

I know, it seems like a vestige of that because those devs are probably hardcore C++ users. Java and C# don't do this and it's never an issue. One relational operator seems to be enough. Also don't like that it's two characters. I think the most common operations should be 1 with 2 characters reserved for more sugary items.

I would not use Swift when I could just use Javascript instead. In fact, I mostly do Javascript for everything now, but I still eye Rust from time to time, to get that native hotness.

Cause even with its issues, its certainly not like C : D

JS is my main with C# a close second. I'm interested in having a compiled language (preferably cross-platform) at the same level but I haven't found one I completely like. I've given up on C++, it's the PHP of compiled languages and no amount of bandaids will fix it, but there's a lot of promise in some of these newer ones built for safety and performance.
 

injurai

Banned
I love Rust, really the only thing holding it back is tooling and libraries. All of which will eventually grow. I think it's going to find a really important niche in the future. If it doesn't take off, it will be derivatives and Rust will be seen as a stepping stone. But It has great corporate backing and great momentum. Something most language don't often get. It very much is the product of many stepping stones less so than one itself.

It's a consolidation of best language design and best practices from the onset of C++ to now.

I know, it seems like a vestige of that because those devs are probably hardcore C++ users. Java and C# don't do this and it's never an issue. One relational operator seems to be enough. Also don't like that it's two characters. I think the most common operations should be 1 with 2 characters reserved for more sugary items.

Ehh, it's really a minor gripe at best. Syntax completion pretty much makes this concern null and void. Rust other syntax quarks are far bigger considerations imo and a lot of them are very well justified for usable language that has to be aware of the many realities of language that lives in interface with a machine.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
For an assignment I had to write a tiny little program in multiple languages, including Haskell and Prolog.

2dBlvAc.gif
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
The assignment required writing a program that averaged the scores in a list, but to write it using five different paradigms.

Imperative: Java
Logical: Prolog
Functional: Haskell
Scripting: Ruby
Object-Oriented: Objective-C

The choice of language was up to us, so I brought a little of the pain upon myself.
 

Somnid

Member
Ehh, it's really a minor gripe at best. Syntax completion pretty much makes this concern null and void. Rust other syntax quarks are far bigger considerations imo and a lot of them are very well justified for usable language that has to be aware of the many realities of language that lives in interface with a machine.

It is minor but fewer symbols goes a long way and it's easier when things are explicit versus implicit. Maybe I could research compiler plugins for Rust, seems like it can't be that hard to fix some of these.
 

injurai

Banned
It is minor but fewer symbols goes a long way and it's easier when things are explicit versus implicit. Maybe I could research compiler plugins for Rust, seems like it can't be that hard to fix some of these.

But it's explicit how it currently is, or maybe I'm not understanding?
 

Koren

Member
Prolog? Haskell I can kind of understand.
I had a whole course on Prolog for my master degree. Interesting, but not the most useful.

I never understood the link between the course and the evaluation, though, it was logic without a single line of prolog...
 

injurai

Banned
The function returns aren't (or at least that's not the preferred style for whatever reason).

I'd argue they are. It's simply the convention of the language to not carry the return keyword. You simply leave the result at the end. If you don't then it returns the default. But within the descriptions of the language, it explicitly conveys what is being done. It just demands language literacy and that's no different than any other language.
 

Koren

Member
The assignment required writing a program that averaged the scores in a list, but to write it using five different paradigms.

Imperative: Java
Logical: Prolog
Functional: Haskell
Scripting: Ruby
Object-Oriented: Objective-C

The choice of language was up to us, so I brought a little of the pain upon myself.
Scripting is a paradigm?

What choices did you have with logical?


In those situations, I'm nasty enough to do functional in Python and imperative in OCaml, just because ^_^
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Scripting is a paradigm?

What choices did you have with logical?

According to the textbook it is. My Ruby was super OOP though.

And we got to choose the language. Prolog was the first one that I saw associated with Logical, and I assumed it was the most popular for that. (aka, the most SO questions about it to figure out wtf I was doing)
 
I know, it seems like a vestige of that because those devs are probably hardcore C++ users. Java and C# don't do this and it's never an issue. One relational operator seems to be enough. Also don't like that it's two characters. I think the most common operations should be 1 with 2 characters reserved for more sugary items.

The biggest problem would probably be the global scope resolution operator. That would definitely be ambiguous if it were a dot. And then once you have that as a different operator, you have to wonder why the global namespace should use a different syntax than any other namespace. So then you get :: for namespaces as well. And then from there you wonder why if globals in namespaces and globals in classes are basically the same thing, why would they use a different syntax?

Using . would also create a problem with name lookup on dependent types. Actually this problem already exists in C++ (see the section at the bottom called "The template disambiguator for dependent names") but having . apply to both types and variables would introduce another ambiguity, and it would make this awful dark corner of C++ more prevalent.

Most people don't even realize this:

Code:
s.template foo<X>();

is valid C++ that compiles, and hopefully it stays that way because it's horrible.
 

Somnid

Member
I'd argue they are. It's simply the convention of the language to not carry the return keyword. You simply leave the result at the end. If you don't then it returns the default. But within the descriptions of the language, it explicitly conveys what is being done. It just demands language literacy and that's no different than any other language.

But you can have multiple returns, which are explicit (is it bad stylistically to mix these?), and I think people are generally for that. I guess my problem is that you don't tell it to return, it just does by convention which other languages have but I haven't encountered that to be best practice. I kind of agree with this: http://www.great-a-blog.co/8-reasons-why-implicit-return-in-modern-languages-is-wrong/. It doesn't add anything and it makes it hard to read, at the very least return as a keyword gets highlighted which makes it easy to skim. I found this to be a bigger problem when returning more complex structures with braces because it's not easy to see where the end is.

The biggest problem would probably be the global scope resolution operator. That would definitely be ambiguous if it were a dot. And then once you have that as a different operator, you have to wonder why the global namespace should use a different syntax than any other namespace. So then you get :: for namespaces as well. And then from there you wonder why if globals in namespaces and globals in classes are basically the same thing, why would they use a different syntax?

Using . would also create a problem with name lookup on dependent types. Actually this problem already exists in C++ (see the section at the bottom called "The template disambiguator for dependent names") but having . apply to both types and variables would introduce another ambiguity, and it would make this awful dark corner of C++ more prevalent.

Most people don't even realize this:

Code:
s.template foo<X>();

is valid C++ that compiles, and hopefully it stays that way because it's horrible.

That's a C++ problem, I don't see why a new language should need to work like that.
 
Top Bottom