nim-wiki/Common-Criticisms.md

35 lines
1.7 KiB
Markdown
Raw Permalink Normal View History

2014-10-21 23:46:56 +00:00
## Nim doesn't require call-site annotation for `var` parameters
This is referring to systems like C#'s: `void foo(ref int myInput){...}; foo(ref a);`. Note the ref on the `foo` call. If this was Nim, it'd be impossible to tell from the call-site that `foo` has the potential to modify `a`.
2014-10-26 12:32:37 +00:00
Possibly. The problem here is that of what mental metaphor is being used. In many languages, heap allocation through pointers is the only method of having objects, and passing them to a function gives the freedom to modify them without any callsite annotations. In Nim, things can be allocated on the stack, and those things need to be treated in the same way as things on the heap.
2014-10-21 23:11:12 +00:00
``` nimrod
2014-10-22 20:31:41 +00:00
proc foo(input: var T) = ...
2014-10-26 12:32:37 +00:00
proc foo(input: ref T) = ...
2014-10-26 12:33:28 +00:00
let a: ref T = ... # `let` says the value of the pointer is immutable
2014-10-21 23:11:12 +00:00
foo(a) # valid, this is Java-style
2014-10-21 23:14:09 +00:00
var b: T = ...
2014-10-26 12:32:37 +00:00
foo(b) # also valid
2014-10-21 23:14:09 +00:00
```
2014-11-15 13:55:11 +00:00
Note that the difference between what happens in Java and what Nim does is simply a matter of efficiency: Nim does not require our `T` to be allocated on the heap, and it certainly allows `b` to be declared with `let`, which will force an compile-time error to be thrown.
## Sum types are weird
In OCaml, sum types are denoted like this:
``` ocaml
type OptionalInt =
| Value of int
| Missing
```
while in Nim they are written like
``` nimrod
type
NodeKind = enum opValue, opAdd, opSub, opMul, opCall
Node = ref object
2014-11-15 13:55:45 +00:00
case kind: NodeKind
2014-11-15 13:55:11 +00:00
of opValue: value: int
of opAdd, opSub, opMul, opCall: kids: seq[Node]
```
2014-11-15 13:55:45 +00:00
While the OCaml way looks better, the Nim version allows for multiple types to have the same values without repetition. It also has the advantage that multiple variants can concisely be matched upon using sets, eg `node.kind in {opSub, opMul}`.