Re: Throw-away variables?
Related: if you want to unpack other datatype, there is `unpack` package: [https://github.com/technicallyagd/unpack](https://github.com/technicallyagd/unpack)
Nim for enterprise software development
What do you think about using Nim in place of Java, C#, and legacy Delphi for enterprise software development? It looks for me as a technology very interesting for the small business market, where there are no resources to rent or invest in hardware and expensive software for huge processing with Java hell etc.
Re: nimble task arguments
yes [https://github.com/nim-lang/nimble/issues/633](https://github.com/nim-lang/nimble/issues/633)
nimble task arguments
Is it possible to pass arguments to nimble tasks? I want to pass the filename to run one test like this: nimble test filename Run
Re: Newbie question: let f = 0.0; why type(f) is float64 instead of float?
`doAssert f is float` is the way to assert the type.
Re: Throw-away variables?
I think this is what you are looking for: [https://nim-lang.org/docs/manual.html#statements-and-expressions-tuple-unpacking](https://nim-lang.org/docs/manual.html#statements-and-expressions-tuple-unpacking) proc returnsTuple(): (int, int, int) = (4, 2, 3) let (x, _, z) = returnsTuple() # apparently this only works for "let" or "var" statements but not for assignments var a, b, c: int (a, b, c) = returnsTuple() # works (a, _, c) = returnsTuple() # this (obviously ?) does NOT work Run
Newbie question: let f = 0.0; why type(f) is float64 instead of float?
This may not be a critical issue but I am trying to understand the basics well to be able to build on them. This is what I think I know: When we declare a variable, we declare it with a type: var i: int = 0 i3: int8 = 1 f: float = 0.0 f32: float32 = 3.14 Run Manual says, any integer literal without a type suffix will have the generic unsigned `int` type (as I understand, with a platform dependent size: 32 or 64-bit). Similarly, `float` is the generic type for floating point literals (specific to this implementation, not platform dependent, always 64-bit). This is probably where I am misinterpreting this but from this info, I expect the following: var i = 0# type int f = 0.0 # type float doAssert $type(i) == "int" echo sizeof(i) # platform dependent, 4 (32-bit) or 8 (64-bit) doAssert $type(f) == "float" # contrary to my expectation, this FAILS echo sizeof(f) # always 8 (64-bit) echo type(f) # apparently the type of "f" is "float64" Run Am I getting this all wrong or, although most probably not that important at all, would it be better (or maybe less confusing at least for me) if `type(f)` was "float"? Thanks in advance
Re: Warning: imported and not used
thank you, that did the trick
Re: Warning: imported and not used
the `-f` command line parameter of Nim will force a rebuilding of ALL modules
Warning: imported and not used
I'm getting warnings about modules imported but not used and I want to fix my code. The second time I compile the warnings to do show up. How do I get the warnings to appear again? The second compile is much faster, so I'm thinking I might have to delete the cache. Is this correct? Where is it?
Re: Problem with macro and identation ...
I think about using inheritance to achieve this. Nim, as pascal, delivers many method to use countable types, like splices, etc. I will write type, which contains seq of strings and I will implement method to get string from this sequence by index. Other method will get index of string. One question is: can I cast enum to integer and make integer to be automatically casted to some enum (compiler should cast this automatically). Is there any generic enum type? Exists there some method like get next value of enum?
Attaching finalizers to ref types (is there a better way?)
Hello, I was looking into creating genuine ref types with finalisers. Is there a way to attach a finalizer to a type without using new(...) ? It seems that Nim is attaching a finaliser statically, but only does that if new() is mentioned somewhere in the program. This is what I found to be working so far, but I feel stupid doing it: type MyObj = ref object of RootObj s: string count: int proc finalize(self:MyObj) = echo "Destroying ", self.s if false: var x:MyObj; new(x, finalize) proc newMyObj(s:string = "") : MyObj = result = MyObj(s:s, count:0) Run Would it make sense perhaps to either repurpose `=destroy` or add proc `=finalize`(self: MyRefObj) ? Thanks, George.
Re: Problem with macro and identation ...
Thanks a lot. I was trying to write macro that generates: enum type and procedure to map value of this enum to related string. I decided to port game based on Freeciv. I'm only developer of this game and introducing a new features takes too long. Freeciv (and my game) is write in C and uses x-includes to generate code on compile time by macros. Given x-includes header takes as „argument” definitions of enum values and related strings by checking in the chain next enum value and related string is defined. It request to name definition in strict way, so this is good example: #define SPECENUM_VAL0 PLAYER_GREEN #define SPECENUM_STR0 "Green" #define SPECENUM_VAL1 PLAYER_RED #define SPECENUM_STR1 "Red" . . . #define SPECENUM_VALN PLAYER_COLOR_n #define SPECENUM_STRN "Some color" #include "genereate_specenum.h" Run I need to understood how macros in nim works to do similar thinks (generate_specenum.h generates enum type and functions translates enum value to related string and vice-versa). I found nim function, which converts enum value to string, but it do similar thing to nim's quote (or quoteStr - I don't remember) or hash/double hash (I don't remember) operator in C preprocesor.
Re: Nim Days: Day 17 Building Sonic Client in Nim
I appreciate your words. Hopefully, I can get more chapters coming. btw, I love dom's work! it's well written and has lots of clear explanations and I think both books can complement each other
Re: How to turn thread spawn call into an async call [redux; Nim 1.0.0]
Not yet AFAIK. We're still waiting on @rayman22201's patches to be finalised.
Re: Nim Coding Examples and Exercises for beginners?
Can you provide any example how to use a modern database (Sqlite3/Mysql/Postgres) with Nim on Windows? I've tried to use Postgres, but libpg was not detected properly.
How to turn thread spawn call into an async call [redux; Nim 1.0.0]
Hi, I've been using a macro to turn thread spawn into an async call that had been [shared previously](https://forum.nim-lang.org/t/3648#22852) on this forum. With Nim 1.0.0 and improvements to asyncdispatch, I'm wondering if this capability made its way into the standard library yet? Sorry if I missed it, I browsed the async* documentation today but couldn't find anything similar. Thanks!
Re: FOSDEM Call for Participation
This description still seems rather "Minimalistic languages" focused. What is the official title of this devroom? Why do we need to focus on minimalistic languages where our devroom was aimed at _emerging languages_?
Re: Problem with macro and identation ...
Hmm, looks like you have quite a bit to understand. Your macro line is also indented too much, it should be on the same indentation level as the type declaration. This line: echo """{name} = enum\n " Run needs to be this: echo "{name} = enum\n " Run because Nim will get confused by the first two quotes and treat the rest of the file as a string. See [here](https://nim-lang.org/docs/tut1.html#lexical-elements-string-and-character-literals) for more info. Your are also trying to write string interpolation without the `strformat` module imported and the `fmt` call before it. For example, the above should be: #top of file import strformat # ... your other code echo fmt"{name} = enum" # the \n is unnecessary because echo already ends with a newline by default # ... your other code Run This is because Nim doesn't support string interpolation this way by default and needs a template called fmt that implements it. So after all those your code then becomes (with some nice formatting for ease of reading): import strformat # This needs to be imported to use fmt"{variable}" in strings type progress_specenum_el = object name: cstring value: string # This needs to be indented and have a star (*) after the macro name to export it to another module macro generate_specenum*(name: string; elements: openarray[progress_specenum_el]): untyped = echo fmt"{name} = enum" echo "BAD," for a in elements: echo fmt"{a.value}," echo "\n" echo fmt"proc string_to_{name}(rname: string): {name} =" echo fmt" const map: seq[progress_specenum_el] = @[repr({elements})]" echo fmt" var b: {name} = low(b)" echo fmt" for a in map:" echo fmt"if a.name == rname:" echo fmt" return b" echo fmt"b=b.succ()" echo fmt" return BAD" Run But, this still will not compile because macros interpret some arguments as `NimNode` instead of what they actually are (not sure if it is a bug or feature), so your `openarray[progress_specenum_el]` just becomes a `NimNode` and your for loop cannot iterate over it. And after that is fixed, your code will run but only print out what you want it to do (and not actually generate anything) because `echo` simply prints values to the console. I was trying to interpret what you are trying to do, and it looks like you are trying to make a macro that generates an enum and a proc that uses that enum. That can definitely be done but requires a greater understanding of the language and how macros work. I could give you a solution, but that would hardly help you learn. A good starting point for macros might be [here](https://flenniken.net/blog/nim-macros/), since it goes over some simple macros and how to generate code. Feel free to update your code based on this, and post here if you have more trouble finding a solution.
Re: Problem with macro and identation ...
Your first file has an extra space on each echo line after the for loop. Remove that and your program will compile. However, that is not how you write a macro. You need to generate NimNodes instead of just printing to the screen. I can give an example when I get to my computer.
Re: question sur les struct or tuple
ok je vais aller regarder ok i'll go watch thank you
Re: Terseness and productivity in Nim vs other languages
I work mainly with JS and Go, and I can tell you I love Nim because I can copy the same program from Go to Nim and it will have like 10 times less code
Error in proc with var and ptr parameters
type VALUE = object d: uint32 #proc init(v: var VALUE) = # working code # v.d = 3 proc init(v: var VALUE | ptr VALUE) = when v is ptr VALUE: v[].d = 1 else: v.d = 2 # compile error var v: VALUE v.init() echo repr v Run testRepr.nim(28, 2) template/generic instantiation of `init` from here testRepr.nim(25, 6) Error: 'v.d' cannot be assigned to This is my mistake or compiler?
Re: Problem with macro and identation ...
`echo` just prints to terminal, like `print` on Python, `puts` on Ruby, `echo` on Bash, etc.
Re: Terseness and productivity in Nim vs other languages
I find that it is more readable when you declare what data type it is. You don't have to comment as much, so it is more orderly IMHO. I think Python have the extreme edge on most language with all these libraries. It seem neural networks and AI in general is leaning towards python, and AI is the future.
Re: question sur les struct or tuple
Have you looked at [Tables](https://nim-lang.org/docs/tables.html) ? They are like hash maps.
Problem with macro and identation ...
Sorry for that (probably) simple question, but I have indentation problems (compiler complains about it): First file: type progress_specenum_el = object name: cstring value: string macro generate_specenum(name: string; elements: openarray[progress_specenum_el]): untyped = echo """{name} = enumn " echo "BAD," for a in elements: echo "{a.value}," echo "n" echo "proc string_to_{name}(rname: string): {name} =n const map: seq[progress_specenum_el] = @[repr({elements})]n var b: {name} = low(b)n for a in map:n if a.name == rname:n return bn b=b.succ()n return BAD" Second file: include includes/progress_utils type generate_specenum("test", [progress_specenum_el("LOL", "LOL"), progress_specenum_el("LOL2", "LOL3")])
code to unpack (msgpack) and "cast" object to
I receive different types of object from network, packed as msgpack. Now i need a construct that creates objects of the given type, to work with them further. I'm struggeling to create a proc/template that does this in one call. My goal is to get something like this: var msgObj = unpack(msgObjEnvelope) ## msgObj is now of type MsgPing, MsgLog etc. Run My data structures looks like this: MessageType* {.pure.} = enum MsgLog, MsgControlReq, MsgControlRes, MsgPing, MsgPong, MsgUntrusted MessageEnvelope* = object messageType*: MessageType # the remote tells me what kind of message was received. msg*: string # the object of MsgPing/MsgLog/... as msgpack MsgBase* = ref object of RootObj version*: byte # more stuff MsgPing* = object of MsgBase # more stuff MsgLog* = object of MsgBase # more stuff Run any idea how i can do this? I could maybe solve this with Object variants, but i do not like that i cannot create obj attributes with the same name: Node = ref object case kind: NodeKind of nkInt: foo: int baa: int of nkFloat: foo: int # <- this would not work and i dont like this, so i would stick with derived objects if possible something: int Run
question sur les struct or tuple
Bonjour, voilà j’arrive du c/c++ j’utilise les struct j’ai fait une correspondance avec (tuple objet) par contre j’aurai aimé me servir de map tel que le c++ me le propose le but : avoir une petite banque de données interne au programme pour faire soit des simulations ou des outils internes. maintenant je n’ai pas trouvé d’exemple sérieux toujours des approches mais juste la définition mais pas comment utilisé concrètement… alors je me suis tourné vers json ai-je raison ??? Hello, here I come from c / c ++ I use the struct I made a correspondence with (tuple object) on the other hand I would have liked to serve as a map as the C ++ offers me the goal : have a small in-house data bank to do either simulations or internal tools. now I have not found a serious example always approaches but just the definition but not how used concretely ... so I turned to json am I right ???
Re: Terseness and productivity in Nim vs other languages
This makes perfect sense, now I have more arguments when recommending Nim to advanced programmers. Thank you for your answers. I am planning to make a tiny toy language(I have a lot of reading and practise to do). Is nimly the way to go? Are there any manuals available? Thank you for all answers, very helpful!
Re: Terseness and productivity in Nim vs other languages
A lot of people find Nim's expressiveness comparable to Python. I find static types in Nim increase productivity even over Python although the ecosystem and tooling are not that rich.
Re: Terseness and productivity in Nim vs other languages
IME Nim code is almost always shorter and it's easy to see why: It doesn't have lines full of `} } }`. ;-) That's hardly an objective bonus to "productivity" because syntax is simply not that important. > How compact are Nim applications? It depends on the coding style. > Can one write a Nim equivalent to a C++ program in dramatically fewer lines > of code? Yes, for multiple reasons: Nim has no header files, Nim's indentation based syntax helps, Nim's macro system allows one to work on the level of the problem domain. > And last but not least, does the macro system significantly reduce the > amounts time and code needed? Yes, if you do it right, see any Karax- or Jester-based application. > For instance JonesForth a complete Forth interpreter written in C took around > 1100 lines of C code. With Nim would the number of lines be reduced? Yes. But notice that C programmers do not care about "reducing the number of lines", C is about `long_identifiers_because_no_namespaces` and about `if (err) goto errorHandler` because "exceptions are bad".
Re: bitops iterator
> I would say 20% That is surprising for me. I would have assumed that Java is not a good choice for a chess engine using (rotated) bitboard representation. As Java uses most of the time reference semantic with indirection, not value semantic. And as Java was not really designed initially for low level bit operations, metaprogramming or using macros like C++ does. (I saw some bitboard C++ code twenty years ago, I think was from Prof. Hyatt but can not really remember his name. Was called rotated-bitboards.)
Re: bitops iterator
Interesting ! I will measure and compare speeds of both...
Re: bitops iterator
Well, regarding java... efficiency is lower than C or Nim... I would say 20% for CPU intensive apps, not more. The memory consumption is also excessive in Java. But conceptualization is convenient. Here is an example of java bit iteration (cryptic but working): protected static final void bitIter(long _uu,Consumer action) {if (_uu==0L) return; long _xx=_uu & -_uu; while (_xx!=0L) {action.accept(_xx);_uu-=_xx;_xx=_uu & -_uu;}} protected static final int log2(long _X) {return 63 - Long.numberOfLeadingZeros(_X);} bitIter(node._P, _RCS -> {int rcs=log2(_RCS);}); Run
Terseness and productivity in Nim vs other languages
I have a question that I have been thinking about since I discovered Nim. How does Nim compare to other languages like C/C++, python,Java as far as productivity and terseness? How compact are Nim applications? Can one write a Nim equivalent to a C++ program in dramatically fewer lines of code? And last but not least, does the macro system significantly reduce the amounts time and code needed? For instance JonesForth a complete Forth interpreter written in C took around 1100 lines of C code. With Nim would the number of lines be reduced? Less time spent coding would benefit employers and corporations being able to spend less money on any given product. And would maybe be easier to maintain and scale.