JuliaKurs23/nb/9_functs.ipynb

1143 lines
28 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"id": "87512b9c",
"metadata": {},
"source": [
"# Funktionen und Operatoren\n",
"\n",
"Funktionen verarbeiten ihre Argumente zu einem Ergebnis, das sie beim Aufruf zurückliefern.\n",
"\n",
"## Formen\n",
"\n",
"Funktionen können in verschiedenen Formen definiert werden:\n",
"\n",
"I. Als `function ... end`-Block\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2cdf33d6",
"metadata": {},
"outputs": [],
"source": [
"function hyp(x,y)\n",
" sqrt(x^2+y^2)\n",
"end"
]
},
{
"cell_type": "markdown",
"id": "d22901e3",
"metadata": {},
"source": [
"II. Als \"Einzeiler\" \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "338f000a",
"metadata": {},
"outputs": [],
"source": [
"hyp(x, y) = sqrt(x^2 + y^2)"
]
},
{
"cell_type": "markdown",
"id": "f14a745f",
"metadata": {},
"source": [
"III. Als anonyme Funktionen\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44319487",
"metadata": {},
"outputs": [],
"source": [
"(x, y) -> sqrt(x^2 + y^2)"
]
},
{
"cell_type": "markdown",
"id": "d8f8978c",
"metadata": {},
"source": [
"### Block-Form und `return`\n",
"\n",
"\n",
"- Mit `return` wird die Abarbeitung der Funktion beendet und zum aufrufenden Kontext zurückgekehrt.\n",
"- Ohne `return` wird der Wert des letzten Ausdrucks als Funktionswert zurückgegeben.\n",
"\n",
"Die beiden Definitionen\n",
"\n",
"```julia\n",
"function xsinrecipx(x)\n",
" if x == 0 \n",
" return 0.0\n",
" end \n",
" return x * sin(1/x)\n",
"end\n",
"```\n",
"und ohne das zweite explizite `return` in der letzten Zeile: \n",
"\n",
"```julia\n",
"function xsinrecipx(x)\n",
" if x == 0 \n",
" return 0.0\n",
" end \n",
" x * sin(1/x)\n",
"end\n",
"```\n",
"\n",
"sind also äquivalent.\n",
"\n",
"\n",
"- Eine Funktion, die \"nichts\" zurückgibt (_void functions_ in der C-Welt), gibt den Wert `nothing` vom Typ `Nothing` zurück. (So wie ein Objekt vom Typ `Bool` die beiden Werte `true` und `false` haben kann, so kann ein Objekt vom Typ `Nothing` nur einen einzigen Wert, eben `nothing`, annehmen.)\n",
"- Eine leere `return`-Anweisung ist äquivalent zu `return nothing`. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "721d72e8",
"metadata": {},
"outputs": [],
"source": [
"function fn(x)\n",
" println(x)\n",
" return \n",
"end\n",
"\n",
"a = fn(2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f6847d6a",
"metadata": {},
"outputs": [],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "483d2b6b",
"metadata": {},
"outputs": [],
"source": [
"@show a typeof(a);"
]
},
{
"cell_type": "markdown",
"id": "66a0d115",
"metadata": {},
"source": [
"### Einzeiler-Form\n",
"\n",
"Die Einzeilerform ist eine ganz normale Zuweisung, bei der links eine Funktion steht.\n",
"\n",
"```julia\n",
"hyp(x, y) = sqrt(x^2 + y^2)\n",
"```\n",
"\n",
"Julia kennt zwei Möglichkeiten, mehrere Anweisungen zu einem Block zusammenzufassen, der an Stelle einer Einzelanweisung stehen kann: \n",
"\n",
"- `begin ... end`-Block\n",
"- Eingeklammerte durch Semikolon getrennte Anweisungen.\n",
"\n",
"In beiden Fällen ist der Wert des Blockes der Wert der letzten Anweisung.\n",
"\n",
"Damit funktioniert auch\n",
"```julia\n",
"hyp(x, y) = (z = x^2; z += y^2; sqrt(z))\n",
"```\n",
"\n",
"und\n",
"```julia\n",
"hyp(x, y) = begin \n",
" z = x^2\n",
" z += y^2 \n",
" sqrt(z) \n",
" end\n",
"```\n",
"\n",
"### Anonyme Funktionen\n",
"\n",
"Anonyme FUnktionen kann man der Anonymität entreisen, indem man ihnen einen Namen zuweist. \n",
"```julia\n",
"hyp = (x,y) -> sqrt(x^2 + y^2)\n",
"```\n",
"Ihre eigentliche Anwendung ist aber im Aufruf einer *(higher order)* Funktion, die eine Funktion als Argument erwartet. \n",
"\n",
"Typische Anwendungen sind `map(f, collection)`, welches eine Funktion auf alle Elemente einer Kollektion anwendet. In Julia funktioniert auch `map(f(x,y), collection1, collection2)`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e07295eb",
"metadata": {},
"outputs": [],
"source": [
"map( (x,y) -> sqrt(x^2 + y^2), [3, 5, 8], [4, 12, 15])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b8ca9baf",
"metadata": {},
"outputs": [],
"source": [
"map( x->3x^3, 1:8 )"
]
},
{
"cell_type": "markdown",
"id": "9ba0e8db",
"metadata": {},
"source": [
"Ein weiteres Beispiel ist `filter(test, collection)`, wobei ein Test eine Funktion ist, die ein `Bool` zurückgibt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12731194",
"metadata": {},
"outputs": [],
"source": [
"filter(x -> ( x%3 == 0 && x%5 == 0), 1:100 )"
]
},
{
"cell_type": "markdown",
"id": "f4af9755",
"metadata": {},
"source": [
"## Argumentübergabe\n",
"\n",
"\n",
"- Beim Funktionsaufruf werden von den als Funktionsargumente zu übergebenden Objekten keine Kopien gemacht. Die Variablen in der Funktion verweisen auf die Originalobjekte. Julia nennt dieses Konzept _pass_by_sharing_. \n",
"- Funktionen können also ihre Argumente wirksam modifizieren, falls es sich um _mutable_ Objekte, wie z.B. `Vector`, `Array` handelt.\n",
"- Es ist eine Konvention in Julia, dass die Namen von solchen argumentmodifizierenden Funktionen mit einem Ausrufungszeichen enden. Weiterhin steht dann üblicherweise das Argument, das modifiziert wird, an erster Stelle und es ist auch der Rückgabewert der Funktion. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d34f0256",
"metadata": {},
"outputs": [],
"source": [
"V = [1, 2, 3]\n",
"\n",
"W = fill!(V, 17)\n",
" # '===' ist Test auf Identität\n",
"@show V W V===W; # V und W benennen dasselbe Objekt "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f83f5e37",
"metadata": {},
"outputs": [],
"source": [
"function fill_first!(V, x)\n",
" V[1] = x\n",
" return V \n",
"end \n",
"\n",
"U = fill_first!(V, 42)\n",
"\n",
"@show V U V===U;"
]
},
{
"cell_type": "markdown",
"id": "7476eab9",
"metadata": {},
"source": [
"## Varianten von Funktionsargumenten\n",
"\n",
"- Es gibt Positionsargumente (1. Argument, 2. Argument, ....) und _keyword_-Argumente, die beim Aufruf durch ihren Namen angesprochen werden müssen. \n",
"- Sowohl Positions- als auch _keyword_-Argumente können _default_-Werte haben. Beim Aufruf können diese Argumente weggelassen werden.\n",
"- Die Reihenfolge der Deklaration muss sein:\n",
" 1. Positionsargumente ohne Defaultwert, \n",
" 2. Positionsargumente mit Defaultwert,\n",
" 3. --- Semikolon ---,\n",
" 4. kommagetrennte Liste der Keywordargumente (mit oder ohne Defaultwert) \n",
"- Beim Aufruf können _keyword_-Argumente an beliebigen Stellen in beliebiger Reihenfolge stehen. Man kann sie wieder durch ein Semikolon von den Positionsargumenten abtrennen, muss aber nicht.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e67e1006",
"metadata": {},
"outputs": [],
"source": [
"fa(x, y=42; a) = println(\"x=$x, y=$y, a=$a\")\n",
"\n",
"fa(6, a=4, 7)\n",
"fa(6, 7; a=4)\n",
"fa(a=-2, 6)"
]
},
{
"cell_type": "markdown",
"id": "1d889283",
"metadata": {},
"source": [
"Eine Funktion nur mit _keyword_-Argumenten wird so deklariert:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e79269ee",
"metadata": {},
"outputs": [],
"source": [
"fkw(; x=10, y) = println(\"x=$x, y=$y\")\n",
"\n",
"fkw(y=2)"
]
},
{
"cell_type": "markdown",
"id": "14d197af",
"metadata": {},
"source": [
"## Funktionen sind ganz normale Objekte\n",
"\n",
" - Sie können zugewiesen werden\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2e0a4b89",
"metadata": {},
"outputs": [],
"source": [
"f2 = sqrt\n",
"f2(2)"
]
},
{
"cell_type": "markdown",
"id": "6f0fef37",
"metadata": {},
"source": [
"- Sie können als Argumente an Funktionen übergeben werden.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c6db6121",
"metadata": {},
"outputs": [],
"source": [
"# sehr naive numerische Integration\n",
"\n",
"function Riemann_integrate(f, a, b; NInter=1000)\n",
" delta = (b-a)/NInter\n",
" s = 0\n",
" for i in 0:NInter-1\n",
" s += delta * f(a + delta/2 + i * delta)\n",
" end\n",
" return s\n",
"end\n",
"\n",
"\n",
"Riemann_integrate(sin, 0, π)"
]
},
{
"cell_type": "markdown",
"id": "b8eb1978",
"metadata": {},
"source": [
"- Sie können von Funktionen erzeugt und als Ergebnis `return`t werden.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "67e640ce",
"metadata": {},
"outputs": [],
"source": [
"function generate_add_func(x)\n",
" function addx(y)\n",
" return x+y\n",
" end\n",
" return addx\n",
"end"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a78dd669",
"metadata": {},
"outputs": [],
"source": [
"h = generate_add_func(4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23b557af",
"metadata": {},
"outputs": [],
"source": [
"h(1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "440b7568",
"metadata": {},
"outputs": [],
"source": [
"h(2), h(10)"
]
},
{
"cell_type": "markdown",
"id": "ab655f0f",
"metadata": {},
"source": [
"Die obige Funktion `generate_add_func()` lässt sich auch kürzer definieren. Der innere Funktionsname `addx()` ist sowieso lokal und außerhalb nicht verfügbar. Also kann man eine anonyme Funktion verwenden.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d0b76e9c",
"metadata": {},
"outputs": [],
"source": [
"generate_add_func(x) = y -> x + y"
]
},
{
"cell_type": "markdown",
"id": "9dcb1129",
"metadata": {},
"source": [
"## Zusammensetzung von Funktionen: die Operatoren $\\circ$ und `|>`\n",
"\n",
"- Die Zusammensetzung _(composition)_ von Funktionen kann auch mit dem Operator $\\circ$ (`\\circ + Tab`) geschrieben werden \n",
"\n",
"$$(f\\circ g)(x) = f(g(x))$$\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fcaf335f",
"metadata": {},
"outputs": [],
"source": [
"(sqrt ∘ + )(9, 16)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "48dd034e",
"metadata": {},
"outputs": [],
"source": [
"f = cos ∘ sin ∘ (x->2x)\n",
"f(.2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ecd0bb3",
"metadata": {},
"outputs": [],
"source": [
"@show map(uppercase ∘ first, [\"ein\", \"paar\", \"grüne\", \"Blätter\"]);"
]
},
{
"cell_type": "markdown",
"id": "64c2f8ca",
"metadata": {},
"source": [
"- Es gibt auch einen Operator, mit dem Funktionen \"von rechts\" wirken und zusammengesetzt werden können _(piping)_\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8cdef694",
"metadata": {},
"outputs": [],
"source": [
"25 |> sqrt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4fd01026",
"metadata": {},
"outputs": [],
"source": [
"1:10 |> sum |> sqrt"
]
},
{
"cell_type": "markdown",
"id": "d8c6e6f3",
"metadata": {},
"source": [
"- Natürlich kann man auch diese Operatoren 'broadcasten' (s. @sec-broadcast). Hier wirkt ein Vektor von Funktionen elementweise auf einen Vektor von Argumenten:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "94691aad",
"metadata": {},
"outputs": [],
"source": [
"[\"a\", \"list\", \"of\", \"strings\"] .|> [length, uppercase, reverse, titlecase]"
]
},
{
"cell_type": "markdown",
"id": "f4b75c54",
"metadata": {},
"source": [
"## Die `do`-Notation\n",
"\n",
"Eine syntaktische Besonderheit zur Definition anonymer Funktionen als Argumente anderer Funktionen ist die `do`-Notation.\n",
"\n",
"Sei `higherfunc(f,a,...)` eine Funktion, deren 1. Argument eine Funktion ist. \n",
"\n",
"Dann kann man `higherfunc()` auch ohne erstes Argument aufrufen und statt dessen die Funktion in einem unmittelbar folgenden `do`-Block definieren:\n",
"\n",
"```julia\n",
"higherfunc(a, b) do x, y\n",
" Körper von f(x,y)\n",
"end\n",
"```\n",
"\n",
"Am Beispiel von `Riemann_integrate()` sieht das so aus:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "76c02df9",
"metadata": {},
"outputs": [],
"source": [
"# das ist dasselbe wie Riemann_integrate(x->x^2, 0, 2)\n",
"\n",
"Riemann_integrate(0, 2) do x x^2 end"
]
},
{
"cell_type": "markdown",
"id": "a708ad3e",
"metadata": {},
"source": [
"Der Sinn besteht natürlich in der Anwendung mit komplexeren Funktionen, wie diesem aus zwei Teilstücken zusammengesetzten Integranden:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3012c9b",
"metadata": {},
"outputs": [],
"source": [
"r = Riemann_integrate(0, π) do x\n",
" z1 = sin(x)\n",
" z2 = log(1+x)\n",
" if x > 1 \n",
" return z1^2\n",
" else\n",
" return 1/z2^2\n",
" end\n",
" end"
]
},
{
"cell_type": "markdown",
"id": "c38a800c",
"metadata": {},
"source": [
"## Funktionsartige Objekte\n",
"\n",
"Durch Definition einer geeigneten Methode für einen Typ kann man beliebige Objekte *callable* machen, d.h., sie anschließend wie Funktionen aufrufen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5de4f59a",
"metadata": {},
"outputs": [],
"source": [
"# struct speichert die Koeffiziente eines Polynoms 2. Grades\n",
"struct Poly2Grad \n",
" a0::Float64\n",
" a1::Float64\n",
" a2::Float64\n",
"end\n",
"\n",
"p1 = Poly2Grad(2,5,1)\n",
"p2 = Poly2Grad(3,1,-0.4)"
]
},
{
"cell_type": "markdown",
"id": "8b0b62a3",
"metadata": {},
"source": [
"Die folgende Methode macht diese Struktur `callable`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0a5cb287",
"metadata": {},
"outputs": [],
"source": [
"function (p::Poly2Grad)(x)\n",
" p.a2 * x^2 + p.a1 * x + p.a0\n",
"end"
]
},
{
"cell_type": "markdown",
"id": "a5149012",
"metadata": {},
"source": [
"Jetzt kann man die Objekte, wenn gewünscht, auch wie Funktionen verwenden.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b271dbf1",
"metadata": {},
"outputs": [],
"source": [
"@show p2(5) p1(-0.7) p1;"
]
},
{
"cell_type": "markdown",
"id": "b355c1b0",
"metadata": {},
"source": [
"## Operatoren und spezielle Formen\n",
"\n",
"- Infix-Operatoren wie `+,*,>,∈,...` sind Funktionen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f71f917",
"metadata": {},
"outputs": [],
"source": [
"+(3, 7)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b19e79cf",
"metadata": {},
"outputs": [],
"source": [
"f = +"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "869917d4",
"metadata": {},
"outputs": [],
"source": [
"f(3, 7)"
]
},
{
"cell_type": "markdown",
"id": "490bceac",
"metadata": {},
"source": [
"- Auch Konstruktionen wie `x[i]`, `a.x`, `[x; y]` werden vom Parser zu Funktionsaufrufen umgewandelt.\n",
"\n",
":::{.narrow}\n",
"\n",
"| | |\n",
"| :-: | :------------ |\n",
"| x[i] | getindex(x, i) |\n",
"| x[i] = z | setindex!(x, z, i) |\n",
"| a.x | getproperty(a, :x) | \n",
"| a.x = z | setproperty!(a, :x, z) |\n",
"| [x; y;...] | vcat(x, y, ...) |\n",
" :Spezielle Formen [(Auswahl)](https://docs.julialang.org/en/v1/manual/functions/#Operators-With-Special-Names)\n",
"\n",
":::\n",
"\n",
"(Der Doppelpunkt vor einer Variablen macht diese zu einem Symbol.)\n",
"\n",
":::{.callout-note}\n",
"Für diese Funktionen kann man eigene Methoden implementieren. Zum Beispiel könnten bei einem eigenen Typ das Setzen eines Feldes (`setproperty!()`) die Gültigkeit des Wertes prüfen oder weitere Aktionen veranlassen. \n",
"\n",
"Prinzipiell können `get/setproperty` auch Dinge tun, die gar nichts mit einem tatsächlich vorhandenen Feld der Struktur zu tun haben. \n",
":::\n",
"\n",
"## Update-Form\n",
"\n",
"Alle arithmetischen Infix-Operatoren haben eine update-Form: Der Ausdruck\n",
"```julia\n",
"x = x ⊙ y\n",
"```\n",
"kann auch geschrieben werden als\n",
"```julia\n",
"x ⊙= y\n",
"```\n",
"\n",
"Beide Formen sind semantisch äquivalent. Insbesondere wird in beiden Formen der Variablen `x` ein auf der rechten Seite geschaffenes neues Objekt zugewiesen. \n",
"\n",
"Ein Speicherplatz- und Zeit-sparendes __in-place-update__ eines Arrays/Vektors/Matrix ist möglich entweder durch explizite Indizierung\n",
"```julia\n",
"for i in eachindex(x)\n",
" x[i] += y[i]\n",
"end\n",
"```\n",
"oder durch die dazu semantisch äquivalente _broadcast_-Form (s. @sec-broadcast):\n",
"```julia\n",
"x .= x .+ y\n",
"```\n",
"\n",
"\n",
"\n",
"## Vorrang und Assoziativität von Operatoren {#sec-vorrang}\n",
"\n",
"Zu berechnende Ausdrücke \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4d92cc97",
"metadata": {},
"outputs": [],
"source": [
" -2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2"
]
},
{
"cell_type": "markdown",
"id": "ec6b89f6",
"metadata": {},
"source": [
"werden vom Parser in eine Baumstruktur überführt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9f607850",
"metadata": {},
"outputs": [],
"source": [
"using TreeView\n",
"\n",
"walk_tree(Meta.parse(\"-2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2\"))"
]
},
{
"cell_type": "markdown",
"id": "68328dda",
"metadata": {},
"source": [
"- Die Auswertung solcher Ausdrücke wird durch \n",
" - Vorrang _(precedence)_ und \n",
" - Assoziativität geregelt.\n",
"- 'Vorrang' definiert, welche Operatoren stärker binden im Sinne von \"Punktrechnung geht vor Strichrechnung\".\n",
"- 'Assoziativität' bestimmt die Auswertungsreihenfolge bei gleichen oder gleichrangigen Operatoren.\n",
"- [Vollständige Dokumentation](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity)\n",
"\n",
"### Assoziativität\n",
"\n",
"Sowohl Addition und Subtraktion als auch Multiplikation und Divison sind jeweils gleichrangig und linksassoziativ, d.h. es wird von links ausgewertet.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "71fdbe34",
"metadata": {},
"outputs": [],
"source": [
"200/5/2 # wird von links ausgewertet als (200/5)/2 "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fc26727a",
"metadata": {},
"outputs": [],
"source": [
"200/2*5 # wird von links ausgewertet als (200/2)*5"
]
},
{
"cell_type": "markdown",
"id": "0253c57a",
"metadata": {},
"source": [
"Zuweisungen wie `=`, `+=`, `*=`,... sind gleichrangig und rechtsassoziativ.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f9891ea",
"metadata": {},
"outputs": [],
"source": [
"x = 1\n",
"y = 10\n",
"\n",
"# wird von rechts ausgewertet: x += (y += (z = (a = 20)))\n",
"\n",
"x += y += z = a = 20 \n",
"\n",
"@show x y z a;"
]
},
{
"cell_type": "markdown",
"id": "9eeccc4c",
"metadata": {},
"source": [
"Natürlich kann man die Assoziativität in Julia auch abfragen. Die entsprechenden Funktionen werden nicht expizit aus dem `Base`-Modul exportiert, deshalb muss man den Modulnamen beim Aufruf angeben. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23fe3c28",
"metadata": {},
"outputs": [],
"source": [
"for i in (:/, :+=, :(=), :^)\n",
" a = Base.operator_associativity(i)\n",
" println(\"Operation $i is $(a)-assoziative\")\n",
"end"
]
},
{
"cell_type": "markdown",
"id": "148b459a",
"metadata": {},
"source": [
"Also ist der Potenzoperator rechtsassoziativ.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d1ad2685",
"metadata": {},
"outputs": [],
"source": [
"2^3^2 # rechtsassoziativ, = 2^(3^2) "
]
},
{
"cell_type": "markdown",
"id": "86c59c17",
"metadata": {},
"source": [
"### Vorrang\n",
"\n",
"- Julia ordnet den Operatoren Vorrangstufen von 1 bis 17 zu: \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9c97eee7",
"metadata": {},
"outputs": [],
"source": [
"for i in (:+, :-, :*, :/, :^, :(=))\n",
" p = Base.operator_precedence(i)\n",
" println(\"Vorrang von $i = $p\") \n",
"end"
]
},
{
"cell_type": "markdown",
"id": "177ecf6d",
"metadata": {},
"source": [
"- 11 ist kleiner als 12, also geht 'Punktrechnung vor Strichrechnung'\n",
"- Der Potenz-Operator `^` hat eine höhere _precedence_.\n",
"- Zuweisungen haben die kleinste _precedence_\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "30c88bf2",
"metadata": {},
"outputs": [],
"source": [
"# Zuweisung hat kleinsten Vorrang, daher Auswertung als x = (3 < 4)\n",
"\n",
"x = 3 < 4 \n",
"x"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b4a0a3ee",
"metadata": {},
"outputs": [],
"source": [
"(y = 3) < 4 # Klammern schlagen natürlich jeden Vorrang\n",
"y"
]
},
{
"cell_type": "markdown",
"id": "0384575c",
"metadata": {},
"source": [
"Nochmal zum Beispiel vom Anfang von @sec-vorrang:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "56488075",
"metadata": {},
"outputs": [],
"source": [
"-2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "543e7874",
"metadata": {},
"outputs": [],
"source": [
"for i ∈ (:^, :+, :/, :(==), :&&, :>, :|| )\n",
" print(i, \" \")\n",
" println(Base.operator_precedence(i))\n",
"end"
]
},
{
"cell_type": "markdown",
"id": "bcb7fc77",
"metadata": {},
"source": [
"Nach diesen Vorrangregeln wird der Beispielausdruck also wie folgt ausgewertet:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "89af1388",
"metadata": {},
"outputs": [],
"source": [
"((-(2^3)+((500/2)/10)==8) && (13 > (7 + 1))) || (9 < 2)"
]
},
{
"cell_type": "markdown",
"id": "509a3955",
"metadata": {},
"source": [
"(Das entspricht natürlich dem oben gezeigten *parse-tree*)\n",
"\n",
"Es gilt also für den Vorrang:\n",
"\n",
"> Potenz > Multiplikation/Division > Addition/Subtraktion > Vergleiche > logisches && > logisches || > Zuweisung\n",
"\n",
"Damit wird ein Ausdruck wie \n",
"```julia\n",
" a = x <= y + z && x > z/2 \n",
"``` \n",
"sinnvoll ausgewertet als `a = ((x <= (y+z)) && (x < (z/2)))`\n",
"\n",
"\n",
"- Eine Besonderheit sind noch\n",
" \n",
" - unäre Operatoren, also insbesondere `+` und `-` als Vorzeichen \n",
" - _juxtaposition_, also Zahlen direkt vor Variablen oder Klammern ohne `*`-Symbol\n",
" \n",
" Beide haben Vorrang noch vor Multiplikation und Division. \n",
"\n",
":::{.callout-important}\n",
"Damit ändert sich die Bedeutung von Ausdrücken, wenn man _juxtaposition_ anwendet:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c134b798",
"metadata": {},
"outputs": [],
"source": [
"1/2*π, 1/2π"
]
},
{
"cell_type": "markdown",
"id": "aafaa2d1",
"metadata": {},
"source": [
"::: \n",
" \n",
"- Im Vergleich zum Potenzoperator `^` gilt (s. [https://discourse.julialang.org/t/confused-about-operator-precedence-for-2-3x/8214/7](https://discourse.julialang.org/t/confused-about-operator-precedence-for-2-3x/8214/7) ):\n",
" \n",
" > Unary operators, including juxtaposition, bind tighter than ^ on the right but looser on the left.\n",
"\n",
"Beispiele:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61fc5df5",
"metadata": {},
"outputs": [],
"source": [
"-2^2 # -(2^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8c609c3b",
"metadata": {},
"outputs": [],
"source": [
"x = 5\n",
"2x^2 # 2(x^2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44a6345d",
"metadata": {},
"outputs": [],
"source": [
"2^-2 # 2^(-2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "660dfb1f",
"metadata": {},
"outputs": [],
"source": [
"2^2x # 2^(2x)"
]
},
{
"cell_type": "markdown",
"id": "0fecdb42",
"metadata": {},
"source": [
"- Funktionsanwendung `f(...)` hat Vorrang vor allen Operatoren\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "198bb0f8",
"metadata": {},
"outputs": [],
"source": [
"sin(x)^2 === (sin(x))^2 # nicht sin(x^2)"
]
},
{
"cell_type": "markdown",
"id": "f153e028",
"metadata": {},
"source": [
"### Zusätzliche Operatoren\n",
"\n",
"Der [Julia-Parser](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm#L13-L31) definiert für zahlreiche Unicode-Zeichen einen Vorrang auf Vorrat, so dass diese Zeichen von Paketen und selbstgeschriebenem Code als Operatoren benutzt werden können. \n",
"\n",
"So haben z.B.\n",
"```julia\n",
" ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ ⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ ⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛\n",
"```\n",
"\n",
"den Vorrang 12 wie Multiplikation/Division (und sind wie diese linksassoziativ) \n",
"und z.B.\n",
"```julia\n",
" ⊕ ⊖ ⊞ ⊟ |++| ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ ⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ \n",
"```\n",
"haben den Vorrang 11 wie Addition/Subtraktion.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.8.5",
"language": "julia",
"name": "julia-1.8"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}