Hi
Is there any plan to include an official web playground to try/share nim
programs online? For example, Rust has Rust Playground, Go and D have something
similar too.
Also, is there any way to check/compare the generated assembly instructions
like in the Rust Playground? Godbolt has
I actually want to catch a specific OSError, an OSError with errorCode
EADDRINUSE. I want to port this to Nim:
[https://gitlab.com/snippets/1903637](https://gitlab.com/snippets/1903637)
Note how I caught the specific exception, otherwise I raise exception again:
Okay I found it.
import os, net
from posix import EADDRINUSE
const sock_addr = "\0com.localserver.myapp.sock"
when isMainModule:
var sock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP)
try:
sock.bindUnix(sock_addr)
echo "connection
> What's the underlying difference between this signature: proc max(a: int; b:
> int): int = and this proc max(a: int, b: int): int =?
As per "Nim in Action", strings are lists of char`s terminated by `'0' (page
29). In the code below, how can I access that null byte?
let s = "Abcd"
echo s[s.len()] == '\0'
# Error: unhandled exception: index 4 not in 0 .. 3 [IndexError]
Run
import net
const sock_addr = "\0com.localserver.myapp.sock"
when isMainModule:
var sock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP)
try:
sock.bindUnix(sock_addr)
echo "connection successful. listening"
while true:
discard 1+1 #
Something similar to
[https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next](https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next)
and
What's Nim's killer app/library? Jester and Karax? None of them has any API
documentation, let alone any websites. It's frustrating not to see any form of
documentation other than "looking at existing the project that uses both".
Same pattern goes for gtk3. The only upto date gtk binding lacks
Very nice but I really wish you included a topic on concurrency and parallelism
and how you would normally use them in Nim. This is something the official
tutorial pt 1 and 2 misses out on and would be a great addition to your
tutorial.
I'm implementing which(1) in nim but I keep looping forever, what's causing
this?
import os, strutils
while isMainModule:
for param in commandLineParams():
for path in getEnv("PATH").split PathSep:
let probe = path & DirSep & param
`import os, strutils proc which*()= for arg in commandLineParams(): #
parallelize here for path in (getEnv "PATH").split PathSep: if existsFile path
& DirSep & arg: echo path & DirSep & arg break which() `
Run
I agree, however it would perform better if there were too many arguments
(which is an edge case). Nonetheless I would love to know how to harness the
multicore capability inside a for loop in Nim.
For reference here's the program in D:
import std.stdio : writeln;
import
Thanks. I missed that equal case.
Hi, my question is not specific to Nim but I'm asking it here because I'm using
it :)
I am debugging a simple iterative binary search but it seems to fail my test.
Here's my impl:
import options
proc index_of*[T](list: openArray[T]; key: T): Option[int] =
var
Looks like someone made a bot that copies my threads. It happened before too:
[https://forum.nim-lang.org/t/5975#37080](https://forum.nim-lang.org/t/5975#37080)
I think the code should explain it better:
import options
let maybe = some[bool](true)
case maybe:
of true:
echo "true"
of false:
echo "false"
of none[bool]():
echo "none"
Run
The compiler complains that
You use static[int], as answered in my thread.
If N is not a compiletime constant, you need to use seq or unchecked_array.
> Why are you using ptrs instead of refs?
So I realized ptr of Husband can be a key to a Table, ref can't.
[https://play.nim-lang.org/#ix=2cCN](https://play.nim-lang.org/#ix=2cCN)
[https://0.30004.com](https://0.30004.com)/
Is there something similar to Java's File.length() method? I would like to know
the immediate disk usage for a directory.
A (1K)
| -> B (3k)
| -> C (9k)
Run
Here, directory A's immediate disk usage is 1k. What proc provides me this
information?
(Reference
thanks
In this code:
proc findMaxCrossingSubArray[T](arr: seq[T]; lo, mid, hi: int64):
SliceResult[T] =
var leftSum = T.min
# ...
Run
I want leftSum to be the minimum value of the type T. The compiler complains:
Error: type mismatch: got
Thank you very much for this
I asked a
question([https://stackoverflow.com/q/59879692/12029705](https://stackoverflow.com/q/59879692/12029705))
in StackOverflow regarding calling Nim from Rust through the C-FFI interface.
In the process of dynamically calling Nim, one needs to instruct the compiler
where to look for Nim
Hi, off-topic question, in your
[https://gist.github.com/Araq/74fc6cfe26e807f7279f65b65500251a#file-binary_trees-nim-L4](https://gist.github.com/Araq/74fc6cfe26e807f7279f65b65500251a#file-binary_trees-nim-L4)
you use the acyclic pragma.
Hi, I am trying to implement a resizing array for learning purposes. My
question is if there is any way to refer to any any array types (considering
array[4, int] and array[10, int] are different types) from a variable.
type
LifoStack*[T] = object
data: array[,
Not all systems have nim installed under /usr/lib/nim. At least not mine, I
installed nim using choosenim.
> extracting the last non-empty line from its output.
This seems like a great idea, provided that it's guaranteed to be the last
non-nmpty line all the time. Mine is
Sorry if this question has been asked but is there anything similar to Rust's
dbg!() macro?
([https://github.com/rust-lang/rfcs/blob/master/text/2361-dbg-macro.md](https://github.com/rust-lang/rfcs/blob/master/text/2361-dbg-macro.md))
It basically lets you print debugging information in
That's what I used for now. As a kindof off topic question, what is the process
of adding new procs to the standard library? Is there any guidelines for it?
I'd like to send PRs to include things like isNumber(string) or
unwrap_or[T](Option[T]) in the standard.
That piece of code looks to be deprecated,
[https://play.nim-lang.org/#ix=2bVL](https://play.nim-lang.org/#ix=2bVL)
I cannot seem to find EInvalidValue in std.
Now that isDigit is deprecated, what's the best way if a string is numeric? For
example "-46.557" should return true
Where did you find out about ValueError? The std module does not mention the
possible thrown exceptions in runtime...
slight nitpick but
import strutils
proc isStringDigit*(str: string): bool =
## Reimplementation of isDigit for strings
if str.len() == 0: return false
for i in str:
if not isDigit(i): return false
return true
assert
Hi I need some tips to cleanup my code. My 4 ctors are very similar, I want to
use templates to avoid duplicate codes. However I don't know if templates
create unique global variable for each of those ctor functions:
import tables, options, sequtils
type
Male =
Recently, Qt has decided that they will offer their open-sourced libraries only
if you have a Qt account. Furthermore their LTS versions are officially behind
a paywall.
[https://www.qt.io/blog/qt-offering-changes-2020](https://www.qt.io/blog/qt-offering-changes-2020)
I hope to start using the
Recently, Kate has announced their support for language servers. Which means if
in future, there's any language server for Nim, Kate can offer some basic IDE
features.
Kind of an off topic question but doesn’t Option[T] obviate the need of
non-nillable types?
type
MatchPool[N] = object # Here, N is an integer
vals: array[N, int]
var mp = MatchPool[3](vals: [2, 4, 1])
Run
Also, can I create new MatchPool of certain int in runtime in the heap?
https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt
I was under the impression that slices are CoW.
Sorry if I sound incoherent but what is PGO and how can I enable it and why is
it not on my default
Recently in response to
[https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching](https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching)/
I came up with my nim solution which was pretty identical to
nvm I just found this
[https://rosettacode.org/wiki/Exceptions#Nim](https://rosettacode.org/wiki/Exceptions#Nim)
Hi, as far as I know Nim has exception tracking:
proc doRaise() {.raises: [IOError].} =
raise newException(IOError, "IO")
Run
1\. Where are the common error types like "IOError" defined in the stdlib?
2\. I want to throw a custom exception. How can I annotate
type
PreferenceError = object of Exception
proc prefersMoreThanCurrent(self, other: Person): bool {.raises: [
PreferenceError].} =
if self.isSingle():
return true
else:
for personRef in self.preferences:
if
I think the code and the error message explains it better:
import options, sequtils
type
Person = object
id: int
name: string
Spouse = object
base: ref Person
engagedTo: Option[ref Person]
ok I simplified the code so I hope people understand my problem better. I don't
quite think dereferencing will help in such a case?
Oh I completely forgot to make the IDs static with {.global.} pragma.
I see I do have other issues. I'll debug them when I get home.
import options
type T = ref object
data: seq[Option[T]]
proc p(t: var T) =
for datum in t.data:
datum = none(T)
Run
/usercode/in.nim(8, 5) Error: 'datum' cannot be assigned to|
---|---
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)
In pursuit of optimizing the following code, I realized that if somehow the
loop is paralleled (i.e. each thread operates on a certain chunk of the array),
the code may execute faster:
import tables, os, parseutils, strutils
proc ytz(args: openArray[string]): uint =
> [https://nim-lang.org/docs/sharedtables.html](https://nim-lang.org/docs/sharedtables.html)
Thank you, I never noticed it. I love Nim's stdlib!
> What would be faster is to read from the file line-by-line.
I always thought calling read() over and over again is fairly expensive. That
said I
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.
Hi, I came across this simple programming task (notice Bonus 2):
[https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching](https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching)/
Here's my solution
> Is this a wrong link? because that doesn't look synchronous.
Ops sorry I had changed the link.
> One important thing to know is that you should never use waitFor in an async
> procedure, use await.
If I use await, the main thread doesn't stop until all the coroutines I create
inside the
I am basically looking for Nim's alternative to Go's `WaitGroup`
package main
import (
"fmt"
"sync"
"time"
)
func main() {
messages := make(chan int)
var wg sync.WaitGroup
// you can also add these one at
In my code I kept making calls to async functions that return future types from
inside a loop. How can I prevent the main thread from finishing before all of
those futures to finish? Note that it's inside a loop that creates are multiple
futures that need finishing.
proc main()
That seems to expect a `vararg`.
I don't exactly know how many times I will be calling a new coroutine before
the loop. The best I can do is add the future to a seq everytime I call a
coroutine:
futures: seq[Future[void]]
for node in parseJson(j)["posts"]:
if
Please consider talking about hosting in your web dev tutorial series as well.
import strutils, sequtils, os, strformat, httpclient, asyncdispatch
# const links: seq[string] = # omitted
const dir = "dir"
os.createDir(fmt"{os.getCurrentDir()}/{dir}")
proc download(link: string; i: int): Future[void] {.async.} =
var fileName =
Brilliant. That worked like charm.
@dwakot unfortunately it didn't wait for the downloads to finish.
Consider posting a blog about your experience with embedded nim.
Hi, I'm still trying to figure out async/await. I am writing a script that
parses a json returned by a forum API and tries to download all the files
described by the json. Writing a synchronous downloader script was a breeze:
> To keep multiple connections open at a time you will need a separate
> HttpClient for each.
Ah that fixes it. Thanks a bunch.
I have an `AsyncHTTPClient`. It
1\. Gets content from a server that returns a json formatted string
2\. From that string, my script looks for specific json nodes that describes
the media the `AsyncHTTPClient` should download. And then the client downloads
the file.
Now I am using the await
Oh...
Thanks might as well delete the thread. This is why I was talking about having
a newbie section
Since I fried my motherboard this afternoon I am now using a windows machine.
I've installed nim with choosenim, even tested nim with a sample hello world
project. However now I can't create a new project with nimble all of a sudden:
PS C:\Users\Adnan\Downloads\proj> nimble i
Just a small question regarding your parseUint, you are taking an argument
called size. If I convert something to a cstring, wouldn't I get a null
terminated string? In which case I can just check if the char is 0 or not to
end the loop.
Very sorry to be annoying but with --gc:arc, is it necessary to close the
memfile?
u9898287@pop-os:~/proj/nimbed$ cat nim.nim
echo "hello world"
u9898287@pop-os:~/proj/nimbed$ nim c -r nim.nim
Hint: system [Processing]
Hint: widestrs [Processing]
Hint: io [Processing]
Hint: nim [Processing]
CC: stdlib_io.nim
CC: stdlib_system.nim
CC:
I'm sorry if this has been discussed before. But wouldn't it nice to have the
forum sorted by sections like beginners/internals/general/news etc?
Hi just wanted to say that I just discovered your video series, and that I
really appreciate it. I am a student myself and I know some very basic html and
css and I'm looking to get started with web development over the quarantine
days. Looking forward to it. Thank you.
In Rust, sometimes the biggest performance overhead is repeated locking of
stdout. To avoid it, one would lock the stdout before the loop. I wonder Nim
requires locking as well.
{
let mut out = File::new("test.out");
let mut buf = BufWriter::new(out);
let
I was under the impression that Linux terminals usually flush on newlines
regardless. There's a chance that the main performance benefit you are gaining
is not from splitting the strings and using the split iter instead. I could be
wrong.
That actually downloads a file in a sequential order. The HTTP Client itself is
async, which means that the client can run in a separate process. What I am
interested in is downloading 1 file concurrently. For example, in Windows I
remember download managers were able to download a file in
But OP is not going to divert the output into `/dev/null`. In a Linux terminal
you don't really gain much benefits from avoiding flushing because it will
flush on a newline regardless.
$ time cat bigfile.txt | ./mine ; cat -n mine.nim
# ...
real0m3.707s
user
Is there something similar to
[https://github.com/porjo/braid](https://github.com/porjo/braid)
I am writing a small tool for my personal use. It's main task is to get a
keyword from the command line and fetch me the relevant documentation
proc/template/macro/const from the nim standard library without me having to
open the web browser and searching for it myself.
What's the best way to
Hello, I would like to bring attention to the fact that the Nim godbolt online
compiler does not seem to work with compiler arguments. Before opening an
issue, I would like to ask the community if I am doing it the wrong way so here
is the link:
Hello, I would like to bring attention to the fact that the Nim godbolt online
compiler does not seem to work with command line arguments. Before opening an
issue, I would like to ask the community if I am doing it the wrong way so here
is the link:
I removed the entire project and started from the scratch and it works now. I
think there was something wrong with my nimcache.
Hi, probably (and most likely) a dumb question but my hello world in jester is
not running any HTTP server.
import asyncdispatch
import jester
routes:
get "/":
resp "Hello world"
runForever()
Run
When I issue nimble build &&
In this example:
import db_sqlite
type
Database* = ref object
db: DbConn
proc newDatabase*(filename = "tweeter.db"): Database =
new result
result.db = open(filename, "", "", "")
Run
What does the first line of the proc
ok I worked around it like I would in C#... using indices.
I think stackoverflow is a better platform for asking such question but I'm
only opening this thread to increase visibility.
Here is the original:
[https://stackoverflow.com/q/60582785/12029705](https://stackoverflow.com/q/60582785/12029705)
The code is about stable matching.
I think its more about sending patches to Kate so it accepts either of these
two:
[https://github.com/nim-lang/langserver/issues/2](https://github.com/nim-lang/langserver/issues/2)
Why didn't he inherit from both Robot and Dog, and delete the poop method? Like
"void poop() = delete;" in C++?
In a proc returning T, if the result variable is never used and if the body
contains no return statement, the compiler should warn the user It may sound
silly, but it could help users debug some logic errors. an int proc silently
returning 0 could make an erroneous code harder to debug. I think
Hello, is there any unit-testing suite that
* Allows me to write unit tests in the same module and
* able to run from `nimble test` command?
I just want to run tests on multiple modules from nimble without creating
separate testing files under `tests/`
Hello. I know that when a type is of `ref`, you need to construct it with
`new(return)` within a function. However how does one construct the type that's
wrapped inside an Option?
type
Tree*[T] = ref object of RootObj
item: T
parent, left, right:
Hello, I know in a function returning a ref type, I need to construct the
result first: `new(result)`
However what if the result is an Option type? I need to construct what's inside
before wrapping it inside an option. How can I do this?
Example code:
type
Tree*[T] = ref
I don't think it's gintro specific. I have never used inheritance in Nim before
so I just need to get started with the basics.
import gintro/[gtk, gobject, gio]
type
Header = ref object of RootObj
base: HeaderBar
text: string
# Header = ref
Hi, I want to create a derived type and call methods of the based type. How
does one achieve this? I was trying to just call the method on the result type
as follows:
type
Header = ref object of HeaderBar
text: string
proc newHeader(): Header =
Hi, about this patch here:
[https://github.com/github/linguist/pull/4900/files](https://github.com/github/linguist/pull/4900/files)
May I ask why .nims is not considered a nim file extension?
Great video!
In a somewhat related topic, I wish they fixed the stdlib documentation
themeing. Everytime you search something in the dark mode, the search results
are very flashy. The box is yellow and the text is bright blue. I wish they fix
the bug soon.
Note that Go has a big FFI overhead:
[https://github.com/dyu/ffi-overhead](https://github.com/dyu/ffi-overhead)
If I may ask, just out of curiosity, what libraries are you missing from Nim?
Hi, I was looking for ways to use Mutex/RWLocks in Nim. I have a list of files
that needs to be downloaded. The download function itself receives a shared
variable (`listener`) and at the end of the download, invokes a method
(`update`) on that listener.
The listener itself is a custom class,
Has this been published yet?
98 matches
Mail list logo