Content deleted Content added
m →Side effects: {{codett|lang=nim|1=}} |
|||
Line 445:
==== Side effects ====
Side effects of functions annotated with the <code>noSideEffect</code> pragma are checked, and the compiler will refuse to compile functions failing to meet those. Side effects in Nim include mutation, global state access or modification, asynchronous code, threaded code, and IO. Mutation of parameters may occur for functions taking parameters of <code>var</code> or <code>ref</code> type: this is expected to fail to compile with the currently-experimental <code>strictFuncs</code> in the future.<ref>{{Cite web |title=Nim Experimental Features: Strict Funcs |url=https://nim-lang.org/docs/manual_experimental.html#strict-funcs}}</ref> The <code>func</code> keyword introduces a shortcut for a <code>noSideEffect</code> pragma.<ref>{{Cite web |title=Nim Manual: Func |url=https://nim-lang.org/docs/manual.html#procedures-func}}</ref>
{{pre|1=
{{codett|lang=nim|func binarySearch[T](a: openArray[T]; elem: T): int}}▼
▲func binarySearch[T](a: openArray[T]; elem: T): int
# is short for...
{{codett|lang=nim|proc binarySearch[T](a: openArray[T]; elem: T): int}} {.noSideEffect.}
{.experimental: "strictFuncs".}
{{codett|lang=nim|type}}
{{codett|lang=nim|1=Node = ref object}}
{{codett|lang=nim|1=le, ri: Node}}
{{codett|lang=nim|1=data: string}}
{{codett|lang=nim|1=func len(n: Node): int =}}
# valid: len does not have side effects
{{codett|lang=nim|1=var it = n}}
{{codett|lang=nim|1=while it != nil:}}
{{codett|lang=nim|1=inc result}}
{{codett|lang=nim|1=it = it.ri}}
{{codett|lang=nim|1=func mut(n: Node) =}}
{{codett|lang=nim|1=let m = n # is the statement that connected the mutation to the parameter}}
{{codett|lang=nim|1=m.data = "yeah" # the mutation is here}}
{{codett|lang=nim|1=# Error: 'mut' can have side effects}}
{{codett|lang=nim|1=# an object reachable from 'n' is potentially mutated}}
}}
==== Function composition ====
|