Re: Dictionary syntax

2020-06-24 Thread cblake
In other words, it seems "excessive" to you because you do not imagine that you 
would never use anything but the stdlib `Table` "behind" `{}`. Never switching 
out something like that is "famous last words" in some circles. :-) So, the 
verbosity guards against the regret of hard-coding.


Re: Dictionary syntax

2020-06-24 Thread cblake
The `{}` syntax is what the Lisp world calls an "association-list" and is more 
general than what the Python world calls a dictionary literal/constructor 
syntax. In Nim `{a:b,c:d, ...}` is just syntactic sugar for `[ (a,b), (c,d), 
... ]` (or `@[]` if you prefer a seq analogy, but it's at compile time when 
either seq or array lengths are "known").

This is a good in that you can use the same syntax for multiple back-end 
associative array implementations (like a simple sorted array, trees, alternate 
hash tables, etc.). In a sense the syntax is only loosely coupled to the 
semantics here. The cost is the slight extra verbosity of tacking on a 
`.toTable`, `toSortedArray`, `.toBST`, `.toBTree` or whatever which is deemed 
an acceptable trade off for the generality. Nim is not Python and you do have 
to put types/type-related things in various places.


Dictionary syntax

2020-06-24 Thread LancerRevX
what does this syntax `var a = {1: "one", 2: "two"}` exist for if it doesn't 
directly create a dictionary (table)? why is it not possible to make a 
dictionary without calling the `toTable` method (`var a = {1: "one", 2: 
"two"}.toTable`)? it seems a bit excessive to me.


Re: Uncle Bob - one syntax to rule them all?

2020-06-04 Thread Araq
> but choosing the right tool for the right purposes.

Nim is the right tool for all purposes. ;-)


Re: Uncle Bob - one syntax to rule them all?

2020-06-04 Thread PMunch
I liked the idea of that parser so I threw together an even better Nim version: 
[https://play.nim-lang.org/#ix=2ogb](https://play.nim-lang.org/#ix=2ogb). It 
parses the format on compile-time and creates a parser that returns a tuple 
with all the arguments. So now all the arguments have the correct type, and on 
runtime it's just a simple tuple access instead of looking through a bunch of 
hash tables for single character arguments. This is what I'd expect to find in 
a Nim codebase (although tidied up a bit, this is just something I threw 
together).


Re: Lambda syntax is awkward

2020-06-03 Thread akavel
That's a good point; and then for 2+ args there's e.g. 
[foldl](https://nim-lang.org/docs/sequtils.html#foldl.t%2Cuntyped%2Cuntyped), 
using `a` and `b` instead of `it`.


Re: Lambda syntax is awkward

2020-06-02 Thread jackhftang
Another technique also seen in std lib.


template twiceIt(input, body: untyped): untyped =
  type T = typeof(input)
  let fn = proc(n: T): T =
let it {.inject.} = n
`body`
  fn(fn(input))


Run


let y = twiceIt 10:
  echo "Gratuitous echo!"
  return it * it


Run


Re: Lambda syntax is awkward

2020-06-02 Thread juancarlospaco
Python lambda is single line only. :) 


Re: Lambda syntax is awkward

2020-06-02 Thread dom96
I wouldn't depend on the do notation. The reason it's experimental is that it 
doesn't fit the language and may be removed entirely eventually.

Personally, I don't think this is too verbose:


let fourthPower = twice(10,
  proc(n: int): int =
echo "Gratuitous echo!"
return n * n
)


Run

It would look very similar in JS. In Python it would simply not be possible.


Re: Lambda syntax is awkward

2020-06-02 Thread treeform
I actually prefer the "original problem" syntax. It's only like couple of 
characters of extra typing. The do, -> and => feel less clear.


Re: Lambda syntax is awkward

2020-06-02 Thread juancarlospaco
[https://github.com/Yardanico/nimpylib/blob/master/src/pylib.nim#L161](https://github.com/Yardanico/nimpylib/blob/master/src/pylib.nim#L161)


Re: Lambda syntax is awkward

2020-06-02 Thread akavel
Hm, not yet there, but arguably somewhat closer with `auto`:


let plusTwo = twice(10) do (n:auto) -> auto:
  echo "Another gratuitious echo"
  n + 1


Run

Maybe this is close enough that now it could be wrapped in some macro to 
shorten even more?


Re: Lambda syntax is awkward

2020-06-02 Thread snej
Oh! I tried using `block` and wondered why it didn't work ... I didn't realize 
parens were necessary.

The `do` notation seems an improvement; it resolves two of the three complaints 
I gave above. If it had better type-inference I'd love it. Maybe that's why 
it's still experimental?

e.g. what I'd like to see is `let plusTwo = twice(10) do (n):`


Re: Uncle Bob - one syntax to rule them all?

2020-06-02 Thread exelotl
Ironically I don't think Uncle Bob would like Nim at all, given our general 
preferance towards straightforward "get shit done" procedural code. For example 
in [this video](https://youtu.be/IRTfhkiAqPw?t=1179) the author critiques some 
of Bob's code and rewrites it in a simple procedural style. The resulting code 
is far more like what I would expect to see in a Nim codebase.


Re: Lambda syntax is awkward

2020-06-02 Thread exelotl
There are some solutions, but all a little awkward.

1\. ["do" 
notation](https://nim-lang.org/docs/manual_experimental.html#do-notation), 
which I believe was moved to _experimental_ just before Nim 1.0, therefore 
might be changed or scrapped in a future Nim version.

Personally I think it's even harder to read than the plain `proc` version. 


let plusTwo = twice(10) do (n:int) -> int:
  echo "Another gratuitious echo"
  n + 1


Run

2\. Sugar module with a [statement list 
expression](https://nim-lang.org/docs/manual.html#statements-and-expressions-statement-list-expression)
 where the last expression in the brackets is treated as the value.

Not idiomatic, wouldn't recommend. 


let plusTwo2 = twice(10, n => (
  echo "Another gratuitious echo";
  n + 1
))


Run

3\. Sugar module with a [block 
expression](https://nim-lang.org/docs/manual.html#statements-and-expressions-block-expression).

I almost like this one! Unfortunately if you remove the brackets, you get " 
_Error: expression expected, but found 'keyword block'_"


let plusTwo3 = twice(10, n => (block:
  echo "Another gratuitious echo"
  n + 1
    ))


Run

Does anyone know, is this a syntax limitation, or could the `=>` operator be 
modified to allow a block expression without brackets? 


Lambda syntax is awkward

2020-06-02 Thread snej
I'm finding Nim's syntax for calling lambdas awkward and verbose.


proc twice[T](input: T, fn: proc(t: T):T):T =
  fn(fn(input))

let fourthPower = twice(10, proc(n: int): int =
  echo "Gratuitous echo!"
  return n * n
)


Run

  * I have to declare parameter and return types. Even C++ lets me omit the 
return type!
  * The nested proc is still inside the outer proc's parentheses, so that has 
to be closed afterwards.
  * And a nitpick: the initial line ends with `=` not `:`, unlike all other 
statements that introduce nested blocks in a proc.



**I 'm aware of the ``sugar`` module.** The `=>` macro makes this a lot better, 
but it only seems to work with single-line lambdas.


let plusTwo = twice(10, (n) => n + 1)


Run

Every attempt I've made to use it in a multi-line lambda fails with syntax 
errors:


let plusTwo = twice(10, (n) =>
  echo "Another gratuitious echo"
  n + 1)  # Error: expected: ')', but got: 'n'


Run

I like that templates and macros can be called with a block as a final 
parameter, but that feature is limited in that the block can't take any 
parameters and can't return a value.

Is there something I've missed? Or are there proposals to improve this in the 
future?

—Jens


Re: Uncle Bob - one syntax to rule them all?

2020-06-02 Thread zulu
> Nim's syntax seems very reasonable. I would use it as-is if there were just a 
> few more libraries like a SQL Server DB driver, XLSX file API. Maybe a few 
> more but nothing off the top of my head.

There are but they are 1 man projects.


Re: Uncle Bob - one syntax to rule them all?

2020-06-02 Thread mratsim
Just like a carpenter has a hammer, screwdrivers, tapes, wrenches, pliers, 
drills, saws for different purposes, developing is not about trying to hammer 
nails with a Swiss Army Knife but choosing the right tool for the right 
purposes.


Re: Uncle Bob - one syntax to rule them all?

2020-06-02 Thread Yardanico
Isn't that what Haxe tries to be? Although it's mainly aimed at game developers 
I think it has the goals that you described here.


Uncle Bob - one syntax to rule them all?

2020-06-01 Thread rbucker
After watching Uncle "Bob" Martin lectures for hours I was left with one 
nagging thought. If we would benefit from one programming language why do we 
have so many? AND where do we go from here? He does talk about different models 
like procedural, structured and functional programming languages and skirts the 
[a] syntax being special purpose; and [b] the syntax is about adding 
constraints or things you cannot do.

Reasons "we" write a lot of BASH scripts is because [a] the SAME syntax is 
available on most platforms [b] it just works [c] it's complete [d] it's simple 
... and so on. For example I have a bash script that I use to build and deploy 
a particular project. It does everything I need but it depends on a 'jot' 
function that is not available on all of the target operating systems. So I 
rewrote it in tcl and it works great. tcl, like bash, has not changed much even 
though there have been numerous releases. The best part is that, like lisp, the 
interpreter is simple to implement. (see golang 3rd party packages and "tcl in 
500 lines")

So what's interesting here, if I say this correctly, is that NIM has both a 
translated (meta) approach to convert nim to (js, c, c++) and can also run as 
an interpreted language. In the past few days I did some example/tutorials on 
ClearLinux (optimized for Intel and SUPER fast). I had a couple of failures 
because of the way ClearLinux handles the /etc folder and that the nim 
installer is only aware of /etc in it's config load path and the default 
nim.cfg.

Nim's syntax seems very reasonable. I would use it as-is if there were just a 
few more libraries like a SQL Server DB driver, XLSX file API. Maybe a few more 
but nothing off the top of my head.

If nim were to heed Uncle Bob... then nim could be the one DSL to rule them 
all. Consider writing your API in NIM and then converting them any other 
language. Client and server side. Right now I'm building some projects that 
would benefit from one language to rule them all. If I were a hiring manager I 
would be looking for devs who could pull that off.

Thanks for listening.


Re: `{}` syntax

2020-04-08 Thread cblake
It's a good-ish summary and your range `[3..5]` is another great example why we 
might want two operators since one could also do a range of `{"RFCs" .. 
"the"}`. The augmented tree actually keeps things like "the number of nodes 
below a node" (or "to the left") and can do a height-of-tree time search to 
find a node of a given rank. You don't really need much more than a `SortedSeq` 
to really demonstrate the interface issue, as mentioned in the long discussion, 
though. (If you want a simpler algorithmic mental model.)

Some clarifications. We don't ever need to break how `Table` is accessed (or 
`seq`). We could only do the `[]` and `{}` for the new bag/sorted bag thing 
(which is not yet impled in Nim (I have C impls to port)). I think the 
extent/impact of this idea was misunderstood because there is so little 
exposure to unkeyed "search" trees. (I've seen some AVL "rope" libraries, the 
Python blist, etc., but it's definitely off the beaten path). A lot of words 
were spilled with me trying to explain that.

Mostly, what I think I am getting pushback on (it's not exactly clear) is 
providing `{}/{}=` for `Table` merely as an "alias" after these impls are all 
in play. That way `{}` could mean "associative-ish" while `[]` could mean 
`positional-ish` as a more global convention like the `add` vs `append` proc or 
other things in `doc/apis.rst`. We could preserve backward compatibility 
forever. Right now `{}=` is only used in the `json` module. The `{}` for 
`Table` is just to make it easier to have the object be either a tree or a 
table. `CritBitTree` and maybe something else might also benefit from that kind 
of operator alias (and might be algorithmically updatable to an instrumented 
tree, actually...Haven't thought about that).

It's possible push back is more general, like "don't ever use two indexing 
operators like `[]/{}` for some core thing like a tree/sortedseq!" or "don't 
ever add an alias for `Table.[]!!`". I don't mean to speak for anyone.

It's not like this is a huge deal to me (however much I may write). It's a 
neglected interface detail because few libraries have multiassociative things 
until late in the syntax game, but we soon will, and Nim's fabulously flexible 
syntax already supports it. It's more consistent with initializer syntax like 
`{:}` and highlights possibly slow associative lookup. I feel like if you like 
`{key:val, ..}` at all more than `@[(key,val),..` then this kind of move would 
be welcome.

Tutorials/intros/explainers of the language do have to decide "Do I favor 
internal consistency/clarity of mentioning `{}` early or do I favor similarity 
to other prog.langs". I think that about covers the real questions. Oh, and the 
alternatives to these are to always use `[]` but with type constructors inside 
to distinguish the "access mode".


Re: `{}` syntax

2020-04-08 Thread spip
That's a long discussion but I find it missing concrete examples. Let it be 
more clear on a fake example. Imagine there's a Bag[string, T] data structure 
implemented with a binary tree, like the following where we have stored some 
data keyed by the words from "Some people don't read the RFCs":


   bag
|
  +-+---+
  | |
 ++--+
+-+-+
 |   || 
  |
 +---++   +--+--+   ++
+---+
 ||   | |   |   #5   || 
 #6   |
+-+ +--+ ++++   | "Some" || 
"the" |
|   #1| |#2| |   #3   ||   #4   |   ++
+---+
| "don't" | | "people" | | "read" || "RFCs" |
+-+ +--+ ++++


Run

The index of an item in the Bag is denoted #index while the keys are the string 
words, and the values are not represented.

Your RFC proposal is to offer a new syntax depending on the type of access:


# Read the value in the "read" node.
let r: T = bag{"read"}

# Update value in the "Some" node.
bag{"Some"} = ...new T data value...

# Read the value of the 2nd node, i.e. the "people" one.
let v: T = bag[2]

# Change the value of the 4th node, i.e. the "RFCs" one.
bag[4] = ...other T value...

# Get the values in nodes 3 to 5, i.e. "Read", "RFCs" and "Some".
let s: seq[T] = bag[3 .. 5]


Run

The proposed {} syntax is used to access data by key in containers while the [] 
syntax is used to access data by position.

This allows querying the data by index range like the last line shows.

This proposal would require to change the way items are accessed in Table for a 
transition period.

Is it a good summary of the RFC? 


`{}` syntax

2020-04-07 Thread cblake
Some people don't read the RFCs often while everyone working with some new 
prog.lang _loves_ syntax debates. :-) So, to get broader exposure, here: 
[https://github.com/nim-lang/RFCs/issues/207](https://github.com/nim-lang/RFCs/issues/207)


Re: Gedit syntax highlighting.

2020-03-15 Thread Stefan_Salewski
No, the gtksourceview based editors Gedit, Aporia and NEd are really no 
recommendation for Nim. Aporia was GTK2 only and has not been updated in the 
last 4 years, Gedit has no Nim support at all, and NEd was written only as a 
plain test for oldgtk3. And gtksourceview itself -- well no one has really 
worked on its C lib code in the last years, internally it is really complicated 
and many features what I may want are missing, and I have not the deep 
understanding, time or motivation to work on it. (To be fair, there is still 
one gtksourceview dev, I can not recall his name, but I think he has made large 
contributions long time ago, then was burned out, and recently tried to come 
back. And there is the gnome boulder guy, but I think he does not care that 
much about gtksourceview itself.)


Re: Gedit syntax highlighting.

2020-03-14 Thread adnan
Hmm turns out they want committed contributors who are willing to maintain the 
.lang file. Which is honestly a fair ask, but I personally think contributing 
to the Nim language server is more useful. Not sure if the gtksourceview based 
editors play very well with it though.


Re: Gedit syntax highlighting.

2020-03-14 Thread Stefan_Salewski
> I am skeptical

I am skeptical too -- why should they care when people not even care to ship an 
up to date file?

A never file is available here: 
[https://github.com/StefanSalewski/NEd](https://github.com/StefanSalewski/NEd)

But it is old too, its from 2016. Was working well with GTK3 gedit until 2 
years ago, but then somehow my gedit install seems to have deleted it locally, 
and I never tried to restore.


Re: Gedit syntax highlighting.

2020-03-14 Thread adnan
I opened an issue in their repository but I am skeptical about them using the 
.lang file, considering it's gtksourceview 2, which is a little bit outdated. 
[https://gitlab.gnome.org/GNOME/gedit/issues/284](https://gitlab.gnome.org/GNOME/gedit/issues/284)


mac nano editor syntax highlight

2020-03-07 Thread pielago
hello I am new to the language found out about it like 6 hour ago and i loved 
it. I looked at them tutorials from the website and I cant wait to start coding 
but, I am not sure if someone already asked this question(does anyone knows how 
to add syntax highlight in nim using terminal mac nano editor) cant wait to use 
NIM in nano terminal !

thanks. 


Re: Gedit syntax highlighting.

2020-02-28 Thread Divy
Oh well, that "shouldn't" be hard? lol


Re: Gedit syntax highlighting.

2020-02-28 Thread dom96
yes, it can. You "just" need to get it into gedit's source code, send them a 
patch.


Gedit syntax highlighting.

2020-02-27 Thread Divy
Ubuntu's inbuilt text editor Gedit is quite good for quick coding.

I use the Python 3 highlighting for Nim but it would be good if we have one for 
Nim too.

Or, is it already there?


Re: Why is `1 +(2 + 3)` a syntax error?

2020-01-07 Thread miran
`1 +(2 + 3)` is translated to `1 +5`, and at that point, `+` is an unary 
operator (e.g. `+5` is a positive five, like `-5` is a negative five).

You can check this if you do `1 - +(2 + 3)`, which will give you `-4` as a 
result.


Is there a syntax sheet of the differences between python 2 and 3 to fix a compiling problem?

2019-11-05 Thread MazukFarnas
I'm honestly finding it hard to learn when I'm working and one piece of code 
works with one software but not another. Like I needed to make a coin flip 
histogram. Issue is that the guy who I found the code for and modified wrote it 
in python 2.x (I heavily modified it because while I am learning I do have HW 
due. I added to it to make it a histogram and fixed it a bit)

I went on Visual Studio got all the libraries for it just to run the code. 
Issue was that VSC ran it hella slow (like were supposed to run it 30 series 
with each series 100times). Matlab handled that ok from what I've heard but my 
code just running it 1000times (not the 3000 times the HW ask for) kinda slows 
the computer. So I thought why not post it into another IDE but the online ones 
(since it's a relatively small amount of code they should be ok) don't seem to 
work since I keep getting syntax errors. I posted the code. Run it 1000 times.


Re: Dot operators and method call syntax.

2019-10-22 Thread jxy
The experimental feature, (), is a mine field. It works if you remove that 
definition.


Dot operators and method call syntax.

2019-10-22 Thread chocobo333
Dosen't work as expected.


import tables

type
Dic = Table[string, int]

template `.`*(self: Dic, field: untyped): int = self[astToStr(field)]
template `.=`*(self: Dic, field: untyped, value: int) =
self[astToStr(field)] = value

proc `()`*(self: int, other: int): int = self * other

var
a: Dic

a.x = 3
a.y = 4
echo a.x # works. `.`(a, x)
echo a.y # works. `.`(a, y)
a.a = 3
echo a["a"] # works.
echo a.a # doesnt work.
# be recognized `()`(a, a)
# maybe it's because variable named "a" exists.


Run

When there exists a variable having same name as right part of `.` , it is not 
recognized as `.` but as `()`


Re: Translate syntax to some of natural language?

2019-10-05 Thread Lachu
I don't think about something similar to symbolic execution. We don't check any 
possibly value, etc. We only show diagram to user (with descriptions).


Re: Translate syntax to some of natural language?

2019-10-02 Thread dponyatov
Does it look like a symbolic execution method?

  * 
[https://www.coursera.org/lecture/software-security/introducing-symbolic-execution-agCNF](https://www.coursera.org/lecture/software-security/introducing-symbolic-execution-agCNF)
  * 
[https://www.youtube.com/watch?v=k6GbaJq-aFo](https://www.youtube.com/watch?v=k6GbaJq-aFo)




Re: Translate syntax to some of natural language?

2019-10-01 Thread Lachu
Ok. I will went this direction. Many years ago I started partnership project, 
which is a computer program and command database with commands description and 
it's insecurity level. Also I have similar database for files. The project was 
abandoned, meanwhile explain shell appear. I now thinking about write similar 
to progress/explain shell reverse engineering tool to create graph of bash 
script. It will translate bash script to graph with human readable description 
of this script. It will save current directory and when it find ls * (for 
example), it will put rectangle and text "ls *; will list each file in /etc/" 
(for example). For pipe it will create tree. For example ls * | grep *.png 
gives "ls * | grep .png: it filter each element containing .png string for: 
list of each file in /home/I" .


Re: Translate syntax to some of natural language?

2019-10-01 Thread dponyatov
Playing with graph representation for programs (in place of programming 
languages), I found that we can easily identify any object with two [polish] 
words: type tag and its name (or scalar literal value). But the problem rises 
right in a moment where we try to describe relation between a few entites. 


Re: Translate syntax to some of natural language?

2019-10-01 Thread dponyatov
You are right, learning computer programming is like learning math -- you must 
not only think, but also must learn the language system, and terminology to 
read anything, and to let anybody else read your thinkings was written.

If you translate only language keywords, it will be just your toy. In Russia, 
we have the 1C accounting system that goes this way -- sometimes it is funny, 
also it is annoying for people who have any programming background.

Programming is not writing code, programming is understanding data structures 
and algorithms, few dozens of English keywords not a problem comparing say 
Red/Black trees implementation.


Translate syntax to some of natural language?

2019-09-29 Thread Lachu
I decided to learn nim and do funny things. As I remembered, long time ago, 
programming language (scientist?) had to translate syntax of some languages to 
use some other natural language than English. This would be especially useful 
for children (not each child must known English, but learning computer 
programming is like learning math - you must think).

I decided to start with Polish, because I live in Poland. I known nim have 
great macro system, which allows to near define own syntax. I need some help:

  1. Some advice/template macro, which could I extend?
  2. How to change statement to not have special meaning, so nim treads it as 
(for example) variable name or how to disable nim statements?
  3. How to pass command line argument to include file with given path - I need 
this, because include/etc. is an English word and I think we shouldn't force 
user to use it



I known people currently doesn't translate syntax (decided it's stupid think), 
but I think it's best way to learn nim possibilities, especially to generate 
config files from source for example and vice-versa ;-) .


Re: Regex substitutions with Perl's syntax... possible with macros?

2019-07-14 Thread Araq
Yeah, it would be possible via macros, but I'm not sure what it should do? 
Replace and return true if there was a replacement?


Regex substitutions with Perl's syntax... possible with macros?

2019-07-13 Thread fredwagner
I know Nim already can do this (from documentation):


 line =~ re"\s*(\w+)\s*\=\s*(\w+)":
  # matches a key=value pair:
  echo("Key: ", matches[0])
  echo("Value: ", matches[1])
elif line =~ re"\s*(\#.*)":
  # matches a comment
  # note that the implicit ``matches`` array is different from the
  # ``matches`` array of the first branch
  echo("comment: ", matches[0])
else:
  echo("syntax error")

Run

What about the following syntax for regex substitution? Can it be emulated with 
macros ou added to the core language? 


string =~ s/regex/replacement/g;


Run

It would be great to have regex syntax sugar in the core language. That would 
make Nim even more practical, while still remaining readable.


Re: method call syntax for more than one argument?

2019-05-29 Thread mratsim
You can probably use a `forth` macro that would do:


forth: c.b.a.f


Run


method call syntax for more than one argument?

2019-05-29 Thread omp
You know how a.f is equivalent to f(a)?

Would it be possible, using macros, to write b.a.f to represent f(a,b), or 
c.b.a.f to represent f(a,b,c), and so on for any number of arguments?

(It makes sense to do b.a.f instead of a.b.f because doing the former is like 
partially applying f to a, and then applying b to that.)

Essentially you could call functions Forth-style by putting the arguments 
before the function.


Re: Nim Syntax ''Skins''

2019-05-17 Thread Libman
The idea of having a binary [AST 
format](https://github.com/tc39/proposal-binary-ast) [is 
finally](https://www.phoronix.com/scan.php?page=news_item=BinaryAST-Proposal)
 [lifting off in the vast swamps of 
JavaScript](https://blog.cloudflare.com/binary-ast/)...

Whether this can benefit languages that compile to JS is a separate discussion, 
but it also has similarity to the Nim "Syntax Skins" idea. Break up the 
compiler into separate programs (or make it executable in partial compilation 
modes): a front-end that generates binary AST, and a backend that converts it 
to C or JS. It would then be possible to fork the front-end to create "sibling 
languages" for Nim that share the same module ecosystem and backend.


Re: Nim Syntax ''Skins''

2019-05-10 Thread chibo
> reading through code on Github and other parts of the web? Simple convention 
> — do not upload to public spaces your preprocessored code, dat simple

btw m$ with their .NET CLI compliant languages - tried to get similar approach, 
but it is a m$, so they ended up with Mono monopoly, heh


Re: Nim Syntax ''Skins''

2019-05-10 Thread chibo
**PRE** **PRO** **CES** **SORS**

We have awesome examples like Pug Stylus Coffeescript, but our lang is already 
compiled, so it easiest things evar, just make preprocessor configuration _(in 
yaml file would be nice)_ available for user custom schemes, which can be 
defined global, or shipped with a project

so code can be compiled to whatever or just plain simple Nim

Our big advantage is absence of Webpack, thing from hell, which is always 
attempting to break your bones, sometimes it ending up with success ~_~ 


Re: How JSON object Syntax relates to table and array syntax?

2018-12-03 Thread mp035
Thanks for the clarification.


Re: How JSON object Syntax relates to table and array syntax?

2018-12-03 Thread mratsim
You're almost spot on.

The limitation is that the types must be known at compile-time. The value can 
be set at runtime.


Re: How JSON object Syntax relates to table and array syntax?

2018-12-02 Thread mp035
Ok, After much RTFM and going through the JSON modules source code I'm going to 
answer my own question, please correct me on anything I have misunderstood:

It looks to me like the argument to the JSON constructor '%*' is not actually a 
data type in the proper sense. It's an expression which is passed to a macro, 
and broken down into NimNodes for evaluation. It has the limitation that it can 
only contain compile-time constants because evaluation of the expression is 
done by the compiler (not by the runtime).


How JSON object Syntax relates to table and array syntax?

2018-12-02 Thread mp035
Hi, I'm very new to Nim, so sorry if this is a noob question.

Firstly, I'd like to thank the Nim developers, Nim really is a fantastic 
system. I discovered it after trying Golang and finding it produced a 6MB 
binary for a simple http client application. The application is designed for an 
OpenWrt device with only 8Mb of flash! Nim on the other hand produces a very 
useable 100kb https client binary in release mode. Wonderful!

Now my question is regarding the data type used to initialise JSON objects. I 
understand that the syntax to create the object is: 


var body = %*{
  "id" : "NIMTEST12345",
  "user" : "futurepoint",
  "password" : "whatever",
  "deviceClass" : 65535,
  "pollingRate" : 5,
  "event" : 0,
  "fault" : false
}


Run

And this works fine. I understand that '%*' is a function name which 
initialises the JSON object, but what type is the argument that follows? I've 
tried:


var device_details = {
  "id" : "NIMTEST12345",
  "user" : "futurepoint",
  "password" : "whatever",
  "deviceClass" : 65535,
  "pollingRate" : 5,
  "event" : 0,
  "fault" : false
}

body = %*(device_details)


Run

but I get the error **Error: type mismatch: got ((string, int)) but expected 
'(string, string)'** at the line **" deviceClass" : 65535** which implies to me 
that tables must have values of a consistent data type.

How can I create the device_details as a separate object (to be referenced by 
other parts of the application) and convert it to json only when required?

Thanks.


syntax highlight of nims, nim.cfg, nimble files broken on github, highlight, sublimetext

2018-10-12 Thread timothee
## on github

  * nim files work
  * config.nims files don't syntax highlight at all:



[https://github.com/kaushalmodi/hello_musl/blob/master/config.nims](https://github.com/kaushalmodi/hello_musl/blob/master/config.nims)

IIUC, syntax highlighting on github is handled in 
[https://github.com/github/linguist](https://github.com/github/linguist) and 
yes they accept PR's

  * foo.nimble files don't syntax highlight at all:



[https://github.com/nim-lang/Nim/blob/devel/tests/deps/zip-0.2.1/zip.nimble](https://github.com/nim-lang/Nim/blob/devel/tests/deps/zip-0.2.1/zip.nimble)

  * nim.cfg seem ok:



[https://github.com/nim-lang/Nim/blob/devel/config/nim.cfg](https://github.com/nim-lang/Nim/blob/devel/config/nim.cfg)
 (nit: some constructs aren't highlighted, but ok)

## using highlight (brew install highlight; works on linux too)

  * nim files work
  * nimble files don't syntax highlight:



eg: tests/deps/zip-0.2.1/zip.nimble

  * nims files don't syntax highlight:



eg: tests/test_nimscript.nims

  * nim.cfg don't syntax highlight:



config/nim.cfg

## sublimetext (with NimLime)

  * nimble files don't syntax highlight



reported in 
[https://github.com/Varriount/NimLime/issues/108](https://github.com/Varriount/NimLime/issues/108)

  * works: nim, nims, nim.cfg




Re: is space around "==" the part of syntax?

2018-08-16 Thread mratsim
The warning was (controversially) added so that people don't inadvertently use 
prefix notation when infix was wanted like 1 ==2.

1 ==2 is parsed as (1, (==`(2)), i.e. `== is prefix while 1 == 2 is parsed as 
(==, 1, 2) so == is infix.

This is especially important for the operator with both prefix and infix forms 
like - and &.

By mistake you could use: a  instead of a & b. More details in 
[#7685](https://github.com/nim-lang/Nim/issues/7685). 


Re: is space around "==" the part of syntax?

2018-08-16 Thread Araq
No, what happens is that with your way of spacing it the `==` is interpreted as 
a unary operator and the error message says that too, only pass an integer 
literal to the `==` in the (sub)expression `==0`.


is space around "==" the part of syntax?

2018-08-15 Thread oyster

echo 1 == 0 # space in the beginning and end of ==

echo 1==0 # no space


Run

can be compiled and run without warning/error

however 


echo 1== 0


Run

can be compiled and run as expected, but there is a warning ` Warning: Number 
of spaces around '==' is not consistent [Spacing]`

the most strange is that nim refuses to compile 


echo 1 ==0


Run

and says 


Error: type mismatch: got 
but expected one of:
proc `==`(x, y: float): bool
proc `==`(x, y: int64): bool
proc `==`[T](x, y: ptr T): bool
proc `==`(x, y: int): bool
proc `==`(x, y: string): bool
proc `==`[T: proc](x, y: T): bool
proc `==`[T](x, y: ref T): bool
proc `==`[T: SomeUnsignedInt](x, y: T): bool
proc `==`(x, y: bool): bool
proc `==`(x, y: char): bool
proc `==`[T](x, y: seq[T]): bool
proc `==`[T: tuple |
object](x, y: T): bool
proc `==`[Enum: enum](x, y: Enum): bool
proc `==`(x, y: float32): bool
proc `==`(x, y: int8): bool
proc `==`(x, y: int32): bool
proc `==`(x, y: int16): bool
proc `==`(x, y: cstring): bool
proc `==`[T](x, y: set[T]): bool
proc `==`(x, y: pointer): bool
proc `==`[I, T](x, y: array[I, T]): bool

expression: ==0


Run


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-08 Thread andrea
I don't think it is a good idea to be explicit about `<` being a proc. For me 
concepts are about (static) duck typing: if it supports `<`, then it satisfies 
the concept. This is good, because I will want to call `<` on members of the 
type. I see concepts as a promise that the code I write next will compile when 
specialized.

I don't really care if `<` is a template or a proc, or possibly it is defined 
on a different type but `a < b` still compiles because of converters.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread dom96
I don't think my proposal is just about the syntax, the underlying semantics 
change significantly. As I've mentioned, the specification becomes more 
concrete and less prone to surprises, i.e. _semantically_ concepts become 
simpler.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread boia01
@cdunn2001 I just replied to your other thread about concepts. I'm not seeing 
the issue you were mentioning.

[https://forum.nim-lang.org/t/2999#25214](https://forum.nim-lang.org/t/2999#25214)


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread zahary
@arnetheduck, regarding run-time polymorphism, there is a planned feature 
called "VTable types". You can read the spec here:

[https://github.com/nim-lang/Nim/blob/5491f1f53b4011785b41b30897b73538d564fd55/doc/manual.rst#L4764](https://github.com/nim-lang/Nim/blob/5491f1f53b4011785b41b30897b73538d564fd55/doc/manual.rst#L4764)


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread zahary
@cdome, there is simple way to ensure that your type conforms to a concept. 
After defining the type and all its procs, put a static assert near the end of 
the module:


static:
  assert Foo is SomeConcept

Run

Future versions of Nim will produce a nice error message describing which 
concept requirement wasn't satisfied.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread zahary
The concept syntax has been discussed already ad nauseam. The current syntax is 
inspired by the ConceptsLite proposal that will eventually make its way into 
C++, so in a distant future it should be familiar to a lot of people.

Considering that the concept definitions will be roughly 0.0005% of all Nim 
code ever written, I find it a bit strange that everyone spends so much time 
arguing about the peculiarities of the syntax. With concepts, it's the 
thousands of functions written to accept concept parameters that are important, 
not the syntax used in the definition of the concept. We should focus on the 
semantics of what can be expressed in a concept rather than how the syntax 
looks like (obviously, beauty here is in the eye of the beholder).

But anyway, here is one of my previous attempts to shot down alternative syntax 
proposals:

[https://github.com/nim-lang/Nim/issues/5770#issuecomment-298886380](https://github.com/nim-lang/Nim/issues/5770#issuecomment-298886380)


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread Araq
Well but we can tweak the semantics endlessly to make it fit ever more varying 
concept descriptions we might want to write, but we will be stuck with the 
syntax. It's not foolish to strive for a good syntax.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread cdunn2001
The problem with `concept` is that it doesn't work with `seq[C]`. If you're not 
aware of that, you can spend a huge amount of time debugging. After you're 
aware, you have to modify your API in potentially difficult ways.

Other than that, I think they're awesome. Not kidding. I love the syntax.

For more discussion, see 
[https://forum.nim-lang.org/t/2999#25214](https://forum.nim-lang.org/t/2999#25214)


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread cdome
IMO, Concept syntax is great from the user perspective. It clearly describes 
what concept can do. From the implementer pointer of view it look like it is 
far too easy to miss concept requirement and you are not sure while writing the 
code you are matching the concept or not.

I don't think what you describe as _declarative_ is going to work, because 
procs are not attached to type in Nim, they are freestanding and can be 
implemented in a different module then type is declared. Therefore you can't 
say if type is matching a concept or not by looking at a type definition. 
Developer can write in a separate file an adaptor to match the concept 
separately from actual object type. I don't have to rewrite objects to match a 
concept and it is a big win in my opinion.

What is missing is a simple proc `concept_check` that can at compile time check 
if concept is matched or not and the _location_ of the mismatch. Developer can 
invoke it in the right place, usually _after_ the procs not at a type def.

P.S. I think we should stop bitch and moan regarding concepts. Concepts are 
GREAT until someone find courage to implement something better. You are not 
happy with the concepts? Go and invest your next 9-16 months in a better 
solution. Once you have implemented it we can compare.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread andrea
Agreed with GULPF: the imperative syntax of concepts makes it more suited to 
some kind of duck typing. Moreover, I find


type
  Comparable = concept x, y
(x < y) is bool


Run

simpler than


type
  Comparable[T] = concept
proc `<`(x, y: T): bool


Run

(if anything it is at least less verbose)


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-07 Thread GULPF
IMO there are good reasons for the current syntax. What if < is implemented 
with a template? What if it has a third argument with a default value? What if 
only `<`(x, y: int): bool` exists, but there's a converter for `T` -> `int`? 
Since Nim has so much flexibility in how to implement things, concepts needs to 
be flexible as well.


Re: Concepts syntax and interfaces - declarative vs procedural

2018-08-06 Thread dom96
Personally I would prefer to simplify the concept syntax.

>From the current syntax:


type
  Comparable = concept x, y
(x < y) is bool


Run

To something like:


type
  Comparable[T] = concept
proc `<`(x, y: T): bool


Run

This would naturally extend to runtime interfaces:


type
  Comparable[T] = interface
proc `<`(x, y: T): bool


Run

As far as I know @zah has his reasons for not wanting to simplify the syntax 
this way. But yes, it's about time to have this discussion so thank you for 
bringing it up.


Concepts syntax and interfaces - declarative vs procedural

2018-08-06 Thread arnetheduck
I'm looking at an issue that proposes using concepts to enforce a simple 
interface - 
[https://github.com/status-im/nim-eth-common/issues/8](https://github.com/status-im/nim-eth-common/issues/8)
 \- and find myself thinking that the syntax is very odd; an interface is 
declared up-front to be implemented by whatever type you pass to the concept 
checker, but this is not the way the concept is written - instead, there's a 
list of expressions that are expected to work for the type to pass, meaning 
that:

  * to implement your type, you have to work "backwards" from the concept, 
executing it in your head and figuring out what the the proc's should look like 
to make sure the concept executes correctly - this makes it hard to work it out 
at a glance (specially looking at some of the more exotic examples in the docs 
- with for loops and all) what proc's you need to write - practical meaning: 
can't copy-paste to implement
  * interfaces are declarative compile time constructs, yet concepts read more 
like procedural code - is there any alternate syntax that captures the 
declarative nature of an interface?
  * could/would you do a macro to provide such a syntax?
  * interfaces can typically be used compile-time or runtime (ie rust traits, 
c++ virtual methods/devirtualization, etc), depending on the types known to the 
compiler at the instantiation point - what about concepts? what would the steps 
be to implement an array of heterogenous types, all conforming ot a concept?




Re: Nim syntax Quiz

2018-03-24 Thread lightness1024
not cool compiler message: 
[https://imgur.com/a/AcANV](https://imgur.com/a/AcANV)

it'd be way better: "not nil only applies to ref types" maybe

we should have a pinned threads about those.


Re: Nim syntax Quiz

2018-03-21 Thread Allin
Some musings;

Beware, I edited title and original post to better reflect the point of the 
thread.

\--

When I first installed Nim 0.13, I accepted that there will be "wtf-moments" 
because I knew that it is work-in-progress. When press release of 1.0 will 
eventually hit the fan, I surely hope there will be flocks of people installing 
Nim just to try it out - just for the evening, for a work day or a weekend. But 
the same amount of tolerance may not be expected then. That's why I think 
progress toward better error messages is very important just now.

\--

Steep entry slope may have been also a blessing so far in the sense that forums 
are not flooded with us beginners, newbies, novices, newcomers, noobies and 
whatnot, but it's not a long-term strategy.

As long as Nim syntax and libraries keep changing, it's also good that www has 
not been filled with outdated solutions. Modern programming is much about first 
finding code and libraries from web and then spending X hours getting the 
versions and dependencies right. Rosetta code was indispensable for me when 
learning (and of) Nim - when 1.0 comes out, make sure that code there is 
up-to-date.

\--

Sorry about the pathos, I just tried to conjure the exasperation of a Nim 
beginner (whose voice may be underrepresented on these forums). It's a 
privilege that even beginners get answered by core devs, but I don't expect 
this to last forever. Hard to imagine Linus reading some beginner forums, let 
alone answering, and if he did, I wouldn't mind the tone.


Re: Nim syntax Quiz

2018-03-21 Thread lightness1024
Hey I have another good one in the category "ignore the compiler and just go 
back to the code".


import db_mysql, tables

type XchgSym = tuple[xchg: string, sym: string]
var xchg_symbol2id = initTable[XchgSym, int]()

# real code:
#let id = db.tryInsertId(sql(qs), m.xchg, m.sym)
# simulation of the result for a stateless environment:
type RetTofTryInsert = type(tryInsertId(open("", "", "", ""), sql""))
let id: RetTofTryInsert = 1
xchg_symbol2id[(xchg:"", sym:"")] = id


change the last line to: 


xchg_symbol2id[(xchg:"", sym:"")] = int(id)


and now it builds.

the compiler output is unhelpful:


comp.nim(11, 15) Error: type mismatch: got (Table[comp.XchgSym, 
system.int], tuple[xchg: string, sym: string], RetTofTryInsert)
but expected one of:
proc `[]=`(s: var string; x: Slice[int]; b: string)
proc `[]=`[T](s: var seq[T]; x: Slice[int]; b: openArray[T])
proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: S)
proc `[]=`[Idx, T](a: var array[Idx, T]; x: Slice[Idx]; b: openArray[T])
proc `[]=`[Idx, T](a: var array[Idx, T]; x: Slice[int]; b: openArray[T])
proc `[]=`[A](t: var CountTable[A]; key: A; val: int)
proc `[]=`[A](t: CountTableRef[A]; key: A; val: int)
proc `[]=`[A, B](t: TableRef[A, B]; key: A; val: B)
proc `[]=`[A, B](t: var Table[A, B]; key: A; val: B)
proc `[]=`[A, B](t: OrderedTableRef[A, B]; key: A; val: B)
proc `[]=`[A, B](t: var OrderedTable[A, B]; key: A; val: B)


Because the type it expects, is in fact not listed here. otherwise we'd have my 
tuple showing up.

The red tilda in VS code (and the column number in the compiler output) points 
to the first [ bracket of the key.

The only clue that got me to save the day, was that it was not showing 
RetTofTryInsert but i64, (I introduced RetTofTryInsert just for the sake of the 
argument). In fact the problem was on the other side of the assignment. Because 
it's NOT an assignment, it's an []= operator and that is very surprising. I 
have no i64 in my types, so changing to int was the fix.


Re: Nim syntax Quiz

2018-03-21 Thread Araq
Unfair quoting IMO, I said

> Or better yet, you ask a beginner who can read a tutorial again to look at 
> some valid syntax. **I 'm not a fan of pathos.**

A friendlier tone would have produced a friendlier answer. But I'm changing 
this to "just always be nice anyway", trying to listen to complaints. 
Independent of the tone I tried my best to improve the situation.

> Because that's what we do, we copy paste a compiler's complaint in google and 
> see if we're not faced with a common mistake, that is solved by checking the 
> first answer on SO as first result in the google response. I've been out of 
> misery in 10 seconds like that for lots of things. Never with nim.

"Nim is not Google friendly" is definitely Nim's problem number one for 
learners, agreed. 


Re: Nim syntax Quiz

2018-03-21 Thread lightness1024
I'm also a beginner and I'm also exasperated by error messages just like you. 
Let's take C#, it's a language that was designed on purpose to be beginner 
friendly, and the compiler outputs messages that are incredible and spot on. 
This makes it frustration-free, and that's one key to adoption.

nim has a steep entry slope, I'm climbing it slowly but it's not without 
frequent requestioning "should I just scrap my proto and move to C# and redo it 
all in 2 days ?"

@Araq your attitude doesn't help with this feeling I'm afraid :'( you often are 
rough with your tone, and stuff like "a beginner who can read a tutorial again" 
that's... hmm

Ok, so the last way too long-lasting head scratching I had (I'll start 
collecting them like you @Allin lol) was when using ".items" and ".keys" 
iterators, it gives out weird errors about fields. I mentioned it in this SO 
question 
[https://stackoverflow.com/q/49407160/893406](https://stackoverflow.com/q/49407160/893406).
 I'm trying to flood SO with everything I can ask that meets the SO standards. 
Because right now, google returns few useful stuff for common beginners 
queries, or the compiler's error messages

Because that's what we do, we copy paste a compiler's complaint in google and 
see if we're not faced with a common mistake, that is solved by checking the 
first answer on SO as first result in the google response. I've been out of 
misery in 10 seconds like that for lots of things. Never with nim. I hope this 
improves.


Re: Nim syntax Quiz

2018-03-20 Thread Araq
"Error: Not all cases are covered" when you have one ')' too much? "Invalid 
indentation" when you have one ')' too much?

Your "quiz" has quite some potential still. 


Re: Nim syntax Quiz

2018-03-20 Thread Allin
On behalf of future Nim beginners I say that is a great reply to my rants. 
Correct and helpful feedback from compiler is even more important than correct 
and helpful feedback from community. When next version comes out, I'll check if 
there's room left for another syntax (error) "quiz".


Re: generic proc not instantiated depending on calling syntax

2018-03-19 Thread Lando
Never lost sleep over undefined and bottom. You are really lucky I'm not 
Libman, this could be a two page excursion. 


Re: generic proc not instantiated depending on calling syntax

2018-03-19 Thread StasB
> The first definition is just a complicated way to write the second one.

Huh. Looks like you're right: 


proc test(T: typedesc): proc(x: T) =
  (proc(x: T) = echo x)

test(string)("foo")


Never occurred to me that you can use it this way.

> I find consistency far more important (Haskell changed my mind quite a bit).

Then you should be disturbed by the fact that Haskell's type system corresponds 
to an inconsistent logic. ;^)


Re: generic proc not instantiated depending on calling syntax

2018-03-19 Thread Lando
@StasB: The first definition is just a complicated way to write the second one. 
typedesc parameters make a proc generic, just like square bracket parameters 
(apart from special binding behaviour). And yes, that's an ambiguity and 
therefore should result in a compiler error.

About the ugliness: you have a point here, but I find consistency far more 
important (Haskell changed my mind quite a bit).


Re: generic proc not instantiated depending on calling syntax

2018-03-19 Thread StasB
@Lando: that would create ambiguities: 


proc test(x: typedesc): proc(x: int) =
  (proc(x: int) = echo x)

proc test(A)(x: int) =
  echo x

test(int)(123) # which one is it?


Personally, I also think it looks far uglier.


Re: generic proc not instantiated depending on calling syntax

2018-03-19 Thread Lando
Never liked using a special bracket character for generic type parameters. 


# this is not a "generic procedure", it's a procedure constructor.
proc threeOf[A](a: A): array[3, A] =
  for i in 0 .. 2:
result[i] = a

# the procedure constructor is called with a type parameter to *produce* a 
proc.
var p = threeOf[int]

# then, the proc is called with a value parameter.
echo p(5)


The fact that the constructor call can happen at compile time and sometimes the 
type parameter can be implied doesn't change that. IMHO it would make more 
sense to use parentheses for type parameters, because that's what we use for 
parametrization anyway: 


proc threeOf(A)(a: A): array[3, A] = ...

threeOf(int)(5)


Type and value parameters are distinguishable by the case of the leading 
character or - for builtins - by syntax highlighting. Square brackets are 
reserved to indcate indexing, as they should.


Re: Nim syntax Quiz

2018-03-19 Thread Araq
The only remaining issue is `var myTuple: MyTuple = [a: 10, b: 10]` which is 
hard to fix. All the others have better error messages now.


Re: generic proc not instantiated depending on calling syntax

2018-03-18 Thread Araq
`x.y[z]` is `(x.y)[z]` and not `x.(y[z])`. There is nothing to disambiguate 
here, expression parsing produces a single consistent AST regardless of the 
involved symbols. There is no "partial call syntax with explicit generic types" 
in Nim's manual. 


Re: generic proc not instantiated depending on calling syntax

2018-03-18 Thread mratsim
It's a known issue. It's hard to disambiguate "test".readMe[uint16]() with a 
bracket expression I suppose since at that time the compiler doesn't know if 
uint16 is a typedesc or an index I suppose.

I think there is a RFC for that: 
[https://github.com/nim-lang/Nim/issues/3502](https://github.com/nim-lang/Nim/issues/3502)


Re: generic proc not instantiated depending on calling syntax

2018-03-18 Thread mashingan
This works


proc identity[T](name: T): T =
  result = name

var n1 = "test".identity
var n2 = 123.identity

echo n1
echo n2



generic proc not instantiated depending on calling syntax

2018-03-18 Thread sflennik
The following program generates an error. Shouldn't it work?


proc readMe[T](name: string): T =
  result = 123'u16
var num = "test".readMe[uint16]()
# var num = readMe[uint16]("test")
echo num


Here are the error messages: 


t.nim(5, 17) template/generic instantiation from here
t.nim(2, 13) Error: cannot instantiate: 'T'


The workaround is to use the commented out line instead.


Re: Nim syntax Quiz

2018-03-17 Thread Allin
Ok, correct answer to the quiz is: 8

You'll find the corrected code below.

As any decent quiz should, one trick question was included: although " 
_inheritance only works with non-final objects_ " is reported as syntax error, 
there's no syntax error at that line; _MyObject_ just should have been declared 
as  " _of RootObj_ ".


type MyTuple = tuple[a: int, b: int]

var myTuple: MyTuple = (a: 10, b: 10)

type MyObject = ref object of RootObj
  a: int

var myObject: MyObject = MyObject(a: 5)

type MySpecialObject = ref object of MyObject

var seqOfStrings: seq[int] = @[]

proc silentProc*() = discard

proc inc(a: var int) = a += 1


Btw1. This discussion is also relevant: 
[https://forum.nim-lang.org/t/3647](https://forum.nim-lang.org/t/3647) It's a 
fact that when the parser gets carried away, it may state some irrelevant line 
as the source of your error. (Due to what StasB stated above).

Again, use the error message line number as a hint, not as a fact.

Btw2. Below is an example of a program that produces - while being a 
pedantically correct error message - quite scary output for a newcomer. A 
friendlier (and admittedly unrealistic to achieve) alternative would be 
something like: _The & operator concatenates two strings, but the procedure 
debug does not return a string. Did you mean: debug("foo" & "bar")_


import logging
debug("foo") & "bar"


The lesson to be learned: Just take nim error messages with a grain of salt (at 
least until Nim 1.x). After all, nim is more programmer-friendly language than 
it's error messages might first suggest. 


Re: Nim syntax Quiz

2018-03-14 Thread mashingan
`nimsuggest` doesn't help?


Re: Nim syntax Quiz

2018-03-14 Thread StasB
I think what it boils down to is that syntactic flexibility and good error 
messages are at odds, simply because the parser can keep going quite a long way 
past the point where it's already clear from the context that the result will 
be semantically invalid, as long as the code happens to be syntactically valid. 
The further it gets from the root cause, the more baffling an error message you 
will get.


Re: Nim syntax Quiz

2018-03-14 Thread Allin
To drive my point home, I shall now reveal what the compiler tells the errors 
are. And boy, they are bogus.


type MyTuple = tuple(a: int, b: int)
# syntax...Error: invalid indentation

var myTuple: MyTuple = [a: 10, b: 10]
# syntax...Error: invalid indentation

type MyObject = ref Object
  a: int
# syntax...Error: undeclared identifier: 'a'

var myObject: MyObject = MyObject(a = 5)
# syntax...Error: invalid expression: 'a = 5'

type MySpecialObject = ref object of MyObject
# syntax...Error: inheritance only works with non-final objects

var seqOfStrings: seq[int] = @[int]
# syntax...Error: internal error: expr(skType); unknown symbol

proc silentProc()* = discard
# syntax...Error: invalid indentation

proc inc(var a: int) = a += 1
# syntax...Error: ')' expected


The issue comes down to 3 problems for a nim novice:

  * How can he trust the compiler (in production) when he cannot trust the 
compiler error messages
  * What's the use of top quality documentation when the compiler tells him to 
search for the solution at wrong place
  * How can he not be scared when a simple error triggers the compiler to 
produce something like core dump (no example on this behaviour above)



Because there is no 1:1 correspondence between syntax errors and their semantic 
consequences, this cannot be simply fixed by search/replacing existing error 
messages. This also should/could not be fixed by complicating the parser (but 
tinkering nimsuggest might be ok, I guess), because looking at the larger 
context is not it's job. That's why I proposed a separate " _common syntax 
error pattern detection tool_ ". I agree that this not something that the core 
devs should be doing at the moment, but this would be a nice project for some 
wannabe core dev out there. (And, eventually, a _quickfix on|off_ compiler 
switch would be nice).

Fortunately detecting all random permutations is not necessary; I believe that 
giving valid quick fix suggestions for the most common 20 syntax errors would 
keep 80% of the beginners happy.

Let me propose a simple short term fix: When the error message is not to be 
trusted, add a question mark to the error message. Instead of stately asserting 
"Invalid intendation", the compiler should politely suggest: "Invalid 
indentation?". This would save our beginner from spending his evening trying to 
fix the error by prefixing/removing leading whitespace (been there, done that).

> But if you do find a crash please at least make sure you report it on GitHub.

Did that. Yesterday my first forum post, today my first issue, tomorrow the 
world? When it comes to nim, I guess I'm now all in.

> the compiler's error message are constantly improving

True. To be honest, most of my beginner syntax errors I have collected long ago 
produce valid error messages now as of 0.18. For example, one of my pain points 
was confusing the usage of : and = operators. That the compiler now gives 
relevant feedback on this confusion is to be highly appreciated by nim 
beginners.

**Quiz 4** , strictly off-topic: try to guess the output 


for x in [0..100]: echo x



Re: Nim syntax Quiz

2018-03-14 Thread Araq
> Quiz 2: Now, imagine that you are a nim newbie. Try to fix the errors with 
> the help of nim manual and compiler error messages. Or,better yet, ask a nim 
> beginner to fix the code and watch the frustration grow.

Or better yet, you ask a beginner who can read a tutorial again to look at some 
valid syntax. I'm not a fan of pathos.

> The errors in the code were not invented by hand, they are real mistakes I 
> admit I have made when learning to nim. Therefore I expect that other 
> beginners will make the same mistakes. The point is that the compiler error 
> messages for these examples are not only unhelpful, they are misleading - if 
> you blindly follow them, you'll end up with even more confusion.

A compiler is not some interactive programming language teacher. That's 
certainly where the future is heading, but currently that is not what a 
compiler is. The compiler's error messages are about pointing out errors. Not 
about guessing what the beginner might have meant instead. For example, in `[a: 
10, b: 10]` that is a valid array construction, but `a` is an undeclared 
identifier. The compiler doesn't look at the larger context to see that you use 
the wrong syntax for tuple creation.

Having said that, the compiler's error message are constantly improving. 
"Imagine somebody trying all sort of token permutations to create tuples" 
wasn't on my radar, but probably for the next version we can improve some of 
these error messages.


Re: Nim syntax Quiz

2018-03-13 Thread Hlaaftana
I guessed `var a: int`, but it turned out to be `@[int]`, which is the mistake 
I thought I'd least likely make


Re: Nim syntax Quiz

2018-03-13 Thread cdome
The error messages improvements is something that is easy to contribute to Nim 
compiler codebase. Pull Requests are welcome.


Re: Nim syntax Quiz

2018-03-13 Thread dom96
> Bonus Question: One of lines crashes the compiler (as of 0.18). Can you 
> detect it?

My bet is `var myObject: MyObject = MyObject(a = 5)`, although it could 
actually be a lot of the lines. You have covered different permutations of 
invalid code quite well.

> I see development of better syntax error messages as one of the high priority 
> tasks in order to make nim more beginner-friendly. I'm namely worried that 
> scary and misleading error messages will intimidate some newbies away from 
> nim before they start to see the light.

I totally agree. But I don't think there is a high chance of serious effort 
being put into it before 1.0 is released. I hope to push a serious 
documentation and usability improvement initiative once 1.0 is released, it 
will be one of the major things that we will work on in versions post-1.0.

Some things are easier to fix than others of course. Crashes in particular 
should be relatively easy to fix. Making errors better is a bit more involved. 
But if you do find a crash please at least make sure you report it on GitHub.

> Do you know other "easily made" syntax errors that produce misleading error 
> messages? Help nim newbies by publishing your cautionary example here (or 
> somewhere).

I don't off the top of my head. But thank you asking people to share theirs. 
It's easy for us to become accustomed to writing code in always the same way, 
and we don't have the time to fuzz the compiler to find strange crashes when 
code is written incorrectly. We definitely rely on newcomers to report these 
issues so we can fix them.


Nim syntax Quiz

2018-03-13 Thread Allin
Hello nimmers!

Below you'll find a nim program that contains syntax errors.

**Quiz 1** : How many errors can you detect just by looking at the code?

**Bonus Question** : One of lines crashes the compiler (as of 0.18). Can you 
detect it?


type MyTuple = tuple(a: int, b: int)

var myTuple: MyTuple = [a: 10, b: 10]

type MyObject = ref Object
  a: int

var myObject: MyObject = MyObject(a = 5)

type MySpecialObject = ref object of MyObject

var seqOfStrings: seq[int] = @[int]

proc silentProc()* = discard

proc inc(var a: int) = a += 1


**Quiz 2** : Now, imagine that you are a nim newbie. Try to fix the errors with 
the help of nim manual and compiler error messages. Or,better yet, ask a nim 
beginner to fix the code and watch the frustration grow.

The errors in the code were not invented by hand, they are real mistakes I 
admit I have made when learning to nim. Therefore I expect that other beginners 
will make the same mistakes. The point is that the compiler error messages for 
these examples are not only unhelpful, they are misleading - if you blindly 
follow them, you'll end up with even more confusion.

As someone who is currently heavily investing in nim, I hope that the user base 
will grow and the language will prosper. I see development of better syntax 
error messages as one of the high priority tasks in order to make nim more 
beginner-friendly. I'm namely worried that scary and misleading error messages 
will intimidate some newbies away from nim before they start to see the light. 
But the current semantically oriented error messages are very helpful for more 
seasoned programmers, so let's not loose them. Instead, I propose that there 
should be a separate syntax error detection phase in compiler pipeline that 
could identify common syntax errors and give helpful quick fix suggestions.

**Quiz 3** : Do you know other "easily made" syntax errors that produce 
misleading error messages? Help nim newbies by publishing your cautionary 
example here (or somewhere).

Happy nimming!


Re: [RFC] List comprehension replacement and syntax

2018-02-08 Thread cdome
@bahm:
could you please add links to IRC logs for discussions already happened?


Re: [RFC] List comprehension replacement and syntax

2018-02-08 Thread cdome
I see a post for the first time, so it is likely has been blocked.

Couple of thoughts in loud:

In Nim expressions have already a proper type, no need wrap then into `let|var` 
assignments. `for x in [1, 2, 3, 4]: if x mod 2 == 0: x else: x + 1` should be 
a already valid.

I think it makes sense `for` expression to return an `iterator` that can be 
folded into any container type afterwards: seq, array or custom.

It is also probably the easiest from the implementation perspective, you just 
sprinkle `yield` in the right places.


Re: [RFC] List comprehension replacement and syntax

2018-02-08 Thread mratsim
I'm surprised no one replied to your thread yet.

The goal is to have "for" be a expression so it could sit on the right-hand 
side of an assignment.

I'm not sure how it will be in practice for the: initialization - for loop - 
return


Re: Nim Syntax ''Skins''

2018-01-30 Thread jlindsay
@dom96 Thank you very much for your reply. Having an open and transparent 
pathway to 1.0 is going to be so important for the community and for fostering 
adoption. Thank you for all of your efforts. I just had my new Nim book arrive 
in the mail this week. Can't wait to read it!


Re: Nim Syntax ''Skins''

2018-01-24 Thread aedt
> #? braces

Thank you god this exists. Best thing I learned today.


  1   2   >