Quantcast
Channel: Controlrede
Viewing all articles
Browse latest Browse all 4677

Nim Writes C Code — And More — For You

$
0
0

When we first heard Nim, we thought about the game. In this case, though, nim is a programming language. Sure, we need another programming language, right? But Nim is a bit different. It is not only cross-platform, but instead of targeting assembly language or machine code, it targets other languages. So a Nim program can wind up compiled by C or interpreted by JavaScript or even compiled by Objective C. On top of that, it generates very efficient code with — at least potentially — low overhead. Check out [Steve Kellock’s] quick introduction to the language.

The fact that it can target different compiler backends means it can support your PC or your Mac or your Raspberry Pi. Thanks to the JavaScript option, it can even target your browser. If you read [Steve’s] post he shows how a simple Hello World program can wind up at under 50K. Of course, that’s nothing the C compiler can’t do which makes sense because the C compiler is actually generating the finished executable, It is a bit harder though to strip out all the overhead yourself.

In addition, nim offers a lot of modern features and package management. There is garbage collection but you can opt out of it and also pick how it runs and when. There’s a pretty robust library for most things including wrappers for OS-specific code and an external GUI library.

The syntax is straightforward and borrows a lot from Python (including the indentation sensitivity which we have mixed feelings about). Here’s an example from the main website:

import strformat
type Person = object name*: string # Field is exported using `*`. age: Natural # Natural type ensures the age is positive.
var people = [ Person(name: "John", age: 45), Person(name: "Kate", age: 30)
] for person in people: # Type-safe string interpolation. echo(fmt"{person.name} is {person.age} years old") 

If you think compiling to C is cheating, don’t forget that’s how C++ started, too. The language itself doesn’t impose any dependencies on your executables unless, of course, you use a library explicitly. Of course, we are more likely to want to build our own language, but it probably wouldn’t have so many features. By the way, Nim is one of the many many choices on the “try it out” website we covered before.


Viewing all articles
Browse latest Browse all 4677

Trending Articles