Hacker News new | ask | show | jobs
by tait 1756 days ago
Hmm. The first sample code on the home page looks a bit odd - can we really create arrays with an unspecified number of entries and fill in every other entry?

  obj = {} 
  for n in 1..10 {     
    if n % 2 == 0 { 
      obj[n] = rand(10\*2) 
    } 
  } 
  echo("We have %s", obj)  
  # {"10": 79, ...}
Let's try it. Copy the source code into the playground. Nope! Error. Try downloading and running again. Nope! Same error.

Hmm. Let's see if we can fix it. What are {} anyway? Oh! Hashes!! Can we really create hashes without.. wait, wait wait. The program is not accessing hashes, it's treating obj like an array. OK. Let's change the {} to [].

Oh joy! It runs! Interesting, the output is "We have [null, null, 51, null, 50, null, 51, null, 86, null, 64]".

Based on the comment in the last line of code, that's not the expected output.

So maybe the %s isn't working? Also, there are 11 elements in the output. Why write "n in 1..10" to create 11 elements? Also, the first value in the result is null; the sample comment suggested it was expecting some kind of value.

My conclusions:

1) It's not clear what the sample code is trying to do.

2) There are at least 2 things wrong with the sample code, at least in terms of some kind of simple way to show off: doesn't run (wrong syntax) and doesn't provide expected output (comment). I am guessing syntax has changed and they didn't update the sample code.

3) The sample code seems to imply 1 based array indexing, but, according to the docs, abs apparantly uses 0 based array indexing.

4) Given the above is the first example sample code on the home page, it is hard to imagine this programming language is stable enough or otherwise optimized for a good onboarding experience.

On the other hand, it appears that yes, we can really create arrays with an unspecified number of entries and fill in every other entry without manually adding array elements.

2 comments

Sorry the example on the docs is definitely not a good one, though I've had a hard time finding something more appropriate that can fit within that block :) Suggestions are more than welcome!

Hash keys need to be string (eg. n -> n.str()), I fixed the example on the homepage.

>can we really create arrays with an unspecified number of entries and fill in every other entry

Seems that was a typo, but you can do that in some languages, either directly (Perl, PHP) or with help (many others). "Autovivification" seems to be the term:

https://en.wikipedia.org/wiki/Autovivification